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,