[leetCode]122.买卖股票的最佳时机II

一次遍历

下面是自己写的一次遍历,思路是每次找到波谷min后开始爬坡,如果没有到转折点就将这次利润和上次利润进行比较,如果大于上次利润累加器sum就加上这次利润减去上次利润将利润最大化

class Solution {
    public int maxProfit(int[] prices) {
        int min = 0;
        int prfit = 0;
        int sum = 0;
        for(int i = 1; i < prices.length; i++){
            if(prices[i] < prices[i-1]) {//更新最小值到达谷底
                min = i;
                prfit = 0;
            }else if(prices[i] > prices[min] && prices[i] > prices[i-1]){//在上升时不断更新prift
                int temp = prfit;//上次利润
                prfit = prices[i] - prices[min];//当前利润
                if(prfit > temp){//如果当前利润比上次利润多则加上这次利润,减去上次利润
                     sum = sum + prfit - temp;
                }
            }
        }
        return sum;
    }
}

下面是官方的一次遍历,每次爬坡将一小段的利润累加,使得利润最大化

class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        for(int i = 1; i < prices.length; i++){
           if(prices[i] > prices[i-1]){
               maxProfit += prices[i] - prices[i-1];
           }
        }
        return maxProfit;
    }
}

峰谷法

寻找曲线的每个波谷和波峰,计算之间的利润,将所有波峰波谷之间的利润求和

class Solution {
    public int maxProfit(int[] prices) {
        int i = 0;
        int valley = prices[0];//波谷
        int peak = prices[0];//波峰
        int maxProfit = 0;
        while(i < prices.length -1){
            //从波峰开始寻找波谷
            while(i < prices.length - 1 && prices[i] >= prices[i+1])
                ++i;
            valley = prices[i];
            //从波谷开始攀爬寻找波峰
            while( i < prices.length - 1 && prices[i] <= prices[i + 1])
                ++i;
            peak = prices[i];
            maxProfit += peak - valley;
        }
        return maxProfit;
    }
}
原文地址:https://www.cnblogs.com/PythonFCG/p/13860003.html