https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/solution/
Solution 1:
TotalProfit=∑i(height(peaki)−height(valleyi))
class Solution {
public int maxProfit(int[] prices) {
int l = prices.length;
if( l <= 0 )return 0;
int valley = prices[0];
int peak = prices[0];
int res= 0;
int i = 0;
while( i < l - 1 ){
while( i < l - 1 && prices[i] >= prices[ i + 1 ])
i ++ ;
valley = prices[i];
while( i < l - 1 && prices[i] <= prices[ i + 1 ])
i ++ ;
peak = prices[i];
res += peak - valley;
}
return res;
}
}
Solution 2:
the sum A+B+C is equal to the difference DD corresponding to the difference between the heights of the consecutive peak and valley.
class Solution {
public int maxProfit(int[] prices) {
int l = prices.length;
if( l <= 0 )return 0;
int res= 0;
for( int i = 1 ; i < l ; i ++ ){
if( prices[i] > prices[i - 1])
res += prices[i] - prices[i-1];
}
return res;
}
}