I got a question on an algorithm question I got in an interview and I can’t seem to figure it out. I understand how it should work, but can’t get it sorted algorithmically.
So assume a firm trades oil barrels and is only able to retain one oil barrel at a time. Assume the company knows the price per barrel for each and every day in a year. So its passed into as an array. How can one write an algorithm to find when to buy and sell?
Here’s an example for just 5 days for simplification:
70 74 73 72 76, for days Monday through Friday respectively.
The best thing to do here is to to buy on Monday (70) sell on Tuesday (74) and then buy on Thursday (72) and sell on Friday (76). Should that be approached recursively? I really want to solve this.
Thanks,
I assume you want to maximise your profit, right?
In that case, you just buy at local minima and sell at local maxima, which would be a simple linear search.
Actually, it is that simple. Proof:
Let’s denote
have is only defined for i in [0, N-1]
now, if we buy on day
kand sell on dayl, we’d havethe profit would be
Let’s denote
For all possible boolean functions
have, we haveThe second line comes from the fact that
max(x, 0) >= x, the third is simple rewrite in terms ofM(i), the fourth comes fromM(i) >= 0.Now, if we set
have(i) == (p(i+1)>p(i)), it would have the same profit as above, which means it is maximal. Also, that means you buy at local minima and sell at local maxima.