https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/solution/

Solution 1:

122. Best Time to Buy and Sell Stock II

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:

122. Best Time to Buy and Sell Stock II

 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;        
    }
}

 

 

 

相关文章:

  • 2021-10-28
  • 2021-07-11
  • 2021-05-17
  • 2021-10-12
  • 2021-04-13
  • 2021-08-17
  • 2021-10-15
猜你喜欢
  • 2021-06-22
相关资源
相似解决方案