I was asked this question while interviewing for a startup and saw this again in the recent contest at
**The question :
You are given the stock prices for a set of days . Each day, you can either buy one unit of stock, sell any number of stock units you have already bought, or do nothing. What is the maximum profit you can obtain by planning your trading strategy optimally?**
Examples ( The input i.e the no of days can vary )
5 3 2 => profit = 0 // since the price decreases each day ,the max profit we can make = 0
1 2 100 => profit = 197
1 3 1 2 =>profit = 3 // we buy at 1 sell at 3 , then we buy at 1 and sell at 2 ..total profit = 3
My Solution :
a) Find the day when the stock price was largest . Keep buying 1 unit of stock till that day.
b) If that day is the last day then quit:
else:
Sell all the stocks on that day and split the array after that day and recurse on the remaining elements
c) merge the profits
e.g 1 4 1 2 3
a) highest stock price on day 2 .. so we buy stock on day 1 and sell it on day 2 ( profit = 3 ) then we recurse on the remaining days : 1 2 3
b) Max price is 3 ( on day 5) so we keep buying stock on day 3 and day 4 and sell on day 5 ( profit = ( 3*2 - 3 = 3 )
c) Total profit = 3 + 3 = 6
The complexity for this turns out to be O(n^2) . this solution passed 10 of the 11 cases but exceeded the time limit on a last test case (i.e the largest input)
So my question is can anyone think of a more efficient solution to this problem ? Is there a dynamic programming solution ?
P.S: this is the first time i am asking a question here. so please let me know if i need to improve/add things to this question
I just solved that problem in a contest site. I think I got a simpler algorithm than the accepted answer.
your logic is correct...
sell at global maxima's..but recursion is not required...
if ith element is global maxima...sell all stocks before i!
Now problem reduces to previous answer+ i+1 to N...
recursion is not required...linearly we can calculate!
here is more simple and easy to understand algo;
Another way to look at it:
In pre-processing, for each element
a[i]
finda[j]
s.t.j > i
and it maximizes(a[j] - a[i])
so, the Best you can do for a price at
a[i]
is Buy ata[i]
and Sell ata[j]
. If there exists noa[j]
s.t.a[j] > a[i]
thena[i]
is not a Buy point at all.Preprocessing time:
O(N)
Here, S[i] is the price at which you should sell a[i].
Summing up total Profit:
O(N)
Another O(n) solution for this task can be done by using local minimum and maximum finding the best deference (profit) between max and min knowing that max should have greater index then min. We also need to look at previous best local min (C# implementation).
0.Start from end of array so that no need to recurse
1. smax = maximum stock price from the list
2.Then find the profit by assuming you have bought all the stocks till smax and you sell it at the price of smax