leetcode——123. 买卖股票的最佳时机 III

public int maxProfit(int[] prices) {
        int n = prices.length;
        if(n<2){
            return 0;
        }
        int[] f = new int[n];
        int[] g = new int[n];
        for(int i = 1,valley = prices[0];i<n;i++){
            valley = Math.min(valley,prices[i]);
            f[i] = Math.max(f[i-1],prices[i] - valley);
        }
        for(int i = n-2,peak = prices[n-1];i>=0;i--){
            peak = Math.max(peak,prices[i]);
            g[i] = Math.max(g[i],peak-prices[i]);
        }

        int max_profit = 0;
        for(int i = 0;i<n;i++){
            max_profit = Math.max(max_profit,f[i]+g[i]);
        }
        return max_profit;
    }

思路啊思路啊思路啊思路啊

设置valley这点以及peak这点我没能想到……

难过哦。

——2020.6.25

猜你喜欢

转载自www.cnblogs.com/taoyuxin/p/13192348.html