I am reading "Introduction To Algorithms". In the maximum subarray problem (Chapter 4), the author claims that the maximum profit of buying and selling a share cannot be calculated just by finding the maximum and minimum of the array. The author speaks of the alternatives such as brute force by calculating all possible combinations of buy and sell dates which would require 0(n^2) time. The other alternative would be to find the maximum subarray of daily-changes in price array.
However, I coded an algorithm which would take 0(n) time and find the maximum profit. This is in 0(n) vs maximum subarray problem of 0(n log n). But I know the authors cannot be wrong. Where am I going wrong ? Is my algorithm correct?
#include <stdio.h>
#include <limits.h>
int main(void)
{
int A[8]={10,8,3,9,7,4,5,10,4};
int i,max,min,currmax,prevmax,n=8;
max=INT_MIN;
min=INT_MAX;
for(i=0;i<n;i++)
{
if(A[i]>max)
{
max=A[i];
prevmax=currmax;
currmax=max-min;
}
if(A[i]<min)
{
min=A[i];
max=INT_MIN;
}
}
if(prevmax>currmax)
printf("%d",prevmax);
else
printf("%d",currmax);
return 0;
}
As given in GeeksForGeeks (http://www.geeksforgeeks.org/divide-and-conquer-maximum-sum-subarray/), the input for daily change in stock prices are A[ ]={-2, -5, 6, -2, -3, 1, 5, -6}. I have taken base price as 10 and have run the algorithm as A[ ]={10,8,3,9,7,4,5,10,4};
Input : 10,8,3,9,7,4,5,10,4
Output: 7
if (max-min > currmax) currmax = max-min;
and just printcurrmax
as your answer. Otherwise you will be incorrect if the answer comes before prevmax. Also you should initializecurrmax
to 0 in case there are no profits to be made. – Lawrence Wu