【重点】【DP】123.买卖股票的最佳时机III

题目

法1:单次遍历,Best!

在这里插入图片描述

class Solution {
    public int maxProfit(int[] prices) {
        int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0;
        for (int i = 1; i < prices.length; ++i) {
            f1 = Math.max(f1, -prices[i]);
            f2 = Math.max(f2, f1 + prices[i]);
            f3 = Math.max(f3, f2 - prices[i]);
            f4 = Math.max(f4, f3 + prices[i]);
        }

        return f4;
    }
}

法2:基于单次买卖+3次遍历

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0, n = prices.length;
        int[] dp1 = new int[n]; // dp[i]从0~i天内的最大收益
        int[] dp2 = new int[n]; // dp[i]从i~n-1天内的最大收益
        int minCost = prices[0], maxPrice = prices[n - 1], ans = 0;
        for (int i = 1; i < n; ++i) {
            minCost = Math.min(minCost, prices[i]);
            dp1[i] = Math.max(dp1[i - 1], prices[i] - minCost);
        }
        for (int i = n - 2; i >= 0; --i) {
            maxPrice = Math.max(maxPrice, prices[i]);
            dp2[i] = Math.max(dp2[i + 1], maxPrice - prices[i]);
        }
        for (int i = 0; i < n; ++i) {
            ans = Math.max(ans, dp1[i] + dp2[i]);
        }

        return ans;
    }
}
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值