Please help me answer this question! 3. (Kleinberg and Tardos, Algorithm Design,
ID: 3551237 • Letter: P
Question
Please help me answer this question!
Explanation / Answer
The trick is to start from the end. Stock trade is easy if time goes backwards!
If you think code is easier to read than words, just skip my explanation, but here goes:
Reading from the end, look at price of that day. Is this the highest price so far (from the end), then sell! The last day (where we start reading) you will always sell.
Then go to the next day (remember, backwards in time). Is it the highest price so far (from all we looked at yet)? - Then sell all, you will not find a better day. Else the prices increase, so buy. continue the same way until the beginning.
The whole problem is solved with one single reverse loop: calculating both the decisions and the profit of the trade.
Here's the code in C-like python
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.