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).
Ideas
Compared to the previous topic, this topic relaxes the trade limit, can do a long trade, but before the next transaction must complete the previous transaction, and the same transaction can only be done once. My train of thought is: If the price rises in the future, then I will buy at the moment. If the price falls in the future, I will sell it at the moment. The result is dividing the array into an ascending sequence of segments, buying at the very beginning of the sequence, and finally selling. For example: [2,1,25,4,5,6,7,2,4,5,1,5]. The array is divided into 5 increments, in the first sequence the profit is 0, the second series profit is 24, the third is 3, the fourth is 3, and the fifth is 4. The total profit is 34. The code is as follows:
1 Public classSolution {2 Public intMaxprofit (int[] prices) {3 intMin = 0;4 intSump = 0;5 intMP = 0;6 7 for(inti = 1; i < prices.length; i++) {8 if(Prices[i] < prices[i-1]){9Sump = Sump +MP;TenMin =i; OneMP = 0; A } - Else -MP = Prices[i]-Prices[min]; the } - - returnSump +MP; - } +}
Leetcode OJ 122. best time to Buy and Sell Stock II