Stock Maximize

https://www.hackerrank.com/challenges/stockmax

Related problems: Best Time to Buy and Sell Stock IBest Time to Buy and Sell Stock IIBest Time to Buy and Sell Stock III.

In previous problems in Leetcode, we can only hold up to one stock. Now, we can hold multiple stocks and try to achieve the maximum profit.

The idea is to scan the array from back to front. Try to find out a monotonic increasing sequence; For example, if the stock prices are

[1, 7, 2, 4, 5, 9, 1, 2, 6]

We start from 6, and store the increasing sequence as

[9, 6].

Note that we actually store the index instead of the value. This sequence represents the points we want to sell the stocks. In other words, the optimal strategy is to continuously buy the stock if it is possible to gain profit. Once we achieve a highest point, sell all of the previous stocks.

In this example, we should buy 1, 7, 2, 4, 5. Then sell all these five stocks at the point 9, get the profit of 8 + 2 + 7 + 5 + 4 = 26. After that, buy 1, 2. Sell them at 6, get the profit of 5 + 4 = 9. The total profit is then 35.

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 4 Trees and Graphs