Say you has an array for which the i-th element is the price of a given-stock on day I.
Design an algorithm to find the maximum profit. You could complete as many transactions as (ie, buy one and sell one share of the stock multiple times). However, engage in multiple transactions for the same time (ie, you must sell the stock before you buy again).
Problem Solving Ideas:
The subject can be bought and sold many times, but at the same time there can only be one share in hand.
This can be bought before each ascending subsequence and sold at the end of the ascending sub-sequence. Equal to the gain of all ascending sub-sequences.
Also, for a ascending subsequence, such as the 1,2,3,4 sequence in 5,1,2,3,4,0, for two operational scenarios:
One, in 1 to buy, 4 to sell;
Two, buy at 1, 2 sell at the same time buy, 3 sell at the same time buy, 4 sell;
The benefits are the same under both operations.
So the algorithm is: scanning prices from beginning to end, if I is larger than i-1, then price[i]–price[i-1] can be counted into the final revenue. This allows you to scan O (n) for maximum benefit.
This problem can is viewed as finding all ascending sequences. For example, given {5, 1, 2, 3, 4}, buy at 1 & sell at 4 are the same as buy at 1 &sell at 2 & buy at 2& SE LL at 3 & Buy @ 3 & sell at 4.
We can scan the array once, and find all pairs of elements that is in ascending order.
Java Code:
Public intMaxprofit (int[] prices) { //This problem can is viewed as finding all ascending sequences. intProfit = 0; for(inti = 1; i< prices.length; i++){ intdiff = prices[i]-prices[i-1]; if(diff > 0) {Profit+=diff; } } returnprofit; }
Reference:
1. http://www.programcreek.com/2014/02/leetcode-best-time-to-buy-and-sell-stock-ii-java/
2. http://blog.unieagle.net/2012/12/04/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Abest-time-to-buy-and-sell-stock-ii/
Leetcode best time to Buy and Sell Stock II