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).
There are several points to note in this question. First of all, the profit is cumulative, not single largest.
And then it's the title that you have to sell before you buy the stock. So it does not exist, only to sell part of the situation.
In this case, the algorithm is simpler than the one that was previously counted as a single max value.
The code is as follows. ~
public class Solution {public int maxprofit (int[] prices) { int profit=0; for (int i=1;i<prices.length;i++) { Profit=profit+math.max (0,prices[i]-prices[i-1]); } return profit;} }
[Leetcode] best time to Buy and Sell Stock II