Given an array, the first element of it is the price of the first day of a given stock.
Design an algorithm to calculate the maximum profit you can get. You can do as many trades as possible (buy and sell a stock).
Note: You cannot participate in multiple transactions at the same time (you must sell the prior stock before buying again).
Example 1:
Input: [7,1,5,3,6,4] Output: 7 explanation: Buy on the 2nd day (stock price = 1), Sell on the 3rd day (stock price = 5), the trade can get Profit = 5-1 = 4. then, on the 4th day (stock price = 3) to buy, on the 5th day (stock price = 6) of the time to sell, the transaction can obtain Profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5] Output: 4 explanation: Buy on the 1th day (stock price = 1), Sell on the 5th day (stock price = 5), the trade can get Profit = 5-1 = 4. Note that you cannot buy stocks on the 1th and 2nd days, and then sell them. since this is part of a multiple transaction, you must sell the stock before you buy it again.
Example 3:
Input: [7,6,4,3,1] Output: 0 explanation: In this case, no transaction is completed, so the maximum profit is 0.
class solution { public int maxprofit (int Span style= "COLOR: #000000" >[] prices) { int result = 0; int tmp = 0; for (int i = 1; i < prices.length; I ++ = prices[i]-prices[i-1); if (tmp > 0 += tmp; return result; }}
LeetCode122. Best time to buy and sell Stocks II