Given an array, its ith element is the price of a given stock on the ith day.
Design an algorithm to calculate the maximum profit you can make. You can make as many trades (buying and selling a stock multiple times) as possible.
Note: You can’t participate in more than one transaction at a time (you must sell your previous shares before buying again).
Example 1:
Input: [7,1,5,3,6,4] Output: 7 Explanation: If you buy on day 2 (stock price = 1) and sell on day 3 (stock price = 5), the exchange will make a profit = 5-1 = 4. Then, by buying on day 4 (stock price = 3) and selling on day 5 (stock price = 6), the exchange makes a profit = 6-3 = 3.Copy the code
Example 2:
Input: [1,2,3,4,5] Output: 4 Explanation: If you buy on day 1 (stock price = 1) and sell on day 5 (stock price = 5), the exchange will make a profit = 5-1 = 4. Note that you can't buy stocks on day 1 and day 2 and then sell them later. Because you're doing multiple trades at once, you have to sell your shares before you can buy them again.Copy the code
Example 3:
Input: [7,6,4,3,1] output: 0 explanation: in this case, no transaction is completed, so the maximum profit is 0.Copy the code
class Solution {
public int maxProfit(int[] prices) {
if( prices.length == 0 ) return 0;
int max = 0;
int left = prices[ 0 ];
for( int i = 1; i < prices.length; i++ ){
if( prices[ i ] < prices[ i - 1 ] ){
max += prices[ i -1 ] - left;
left = prices[ i ];
}
}
max += prices[ prices.length -1 ] - left;
returnmax; }}Copy the code
If the current value is smaller than the previous value, subtract the lvalue from the previous value and add it to the result. At the same time, update the lvalue to the current value. And then finally we need to add the last value minus the lvalue.