面试经典 150 题 (八)

将所有的递增段的增加值叠加起来
class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length <= 1){
            return 0;
        }
        int pre = 0;
        int p = 1;
        int maxPro = 0;
        int start = 0;
        boolean flag = false;   //标志当前是否是递增
        while(p < prices.length){
            if(prices[pre] < prices[p]){
                if (flag == false){
                    flag = true;
                    start = pre;
                }
            }else{
                if (flag == true){
                    flag = false;
                    maxPro = maxPro +  (prices[pre] - prices[start]);
                }
            }
            pre++;
            p++;
        }
        if (flag){
            maxPro = maxPro + (prices[pre] - prices[start]);
        }
        return maxPro;
    }
}
上边问题想复杂了
class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length <= 1){
            return 0;
        }
        int maxPro = 0;
        for (int i = 1; i < prices.length; i++){
            if(prices[i - 1] < prices[i]){
                maxPro = maxPro + (prices[i] - prices[i - 1]);
            }
        }
        return maxPro;
    }
}
动态规划
class Solution {
    public int maxProfit(int[] prices) {
        int length = prices.length;
        if(length <= 1){
            return 0;
        }
        int[][] dp = new int[length][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for(int i = 1; i < length; i++){
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i-1][0] - prices[i], dp[i-1][1]);
        }
        return dp[length-1][0];
    }
}
                    
                
                
            
        
浙公网安备 33010602011771号