[Leetcode]123.Best Time to Buy and Sell Stock III

问题描述:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

思路:

这道题目的标签里有动态规划,所以我一开始是用动态规划的方法做的。用m[i][j]记录i到j的最大利润。提交的时候显示超时了,显然 O(n2) 的复杂度不行了。
后来观察代码发现,计算两次交易最大利润的时候只用到了m[n][n]中的第一行和最后一行,那么显然可以优化了。
再分析问题可以发现,要计算两次交易的最大利润,可以把价格数组划分成两部分,prices[0…k]和prices[k…n-1],分别计算出两部分的最大利润,相加即可,复杂度为 O(n)
0到k的最大利润,从前往后计算,需要记录0到k之间的最小价格;k到n-1的最大利润,从后往前计算,需要记录k到n-1之间的最大价格。

代码:

public int maxProfit(int[] prices) {
        if (prices.length == 0 || prices == null) {
            return 0;
        }
        int n = prices.length;
        int[] min_price_from_start = new int[n];
        int[] max_price_to_end = new int[n];
        int[] max_profit_from_start = new int[n];
        int[] max_profit_to_end = new int[n];
        min_price_from_start[0] = prices[0];
        max_price_to_end[n-1] = prices[n-1];
        max_profit_from_start[0] = 0;
        max_profit_to_end[n-1] = 0;

        for (int i = 1; i < n; i++) {
            min_price_from_start[i] = Math.min(prices[i], min_price_from_start[i-1]);
            max_profit_from_start[i] = Math.max(prices[i] - min_price_from_start[i], max_profit_from_start[i-1]);
        }
        for (int i = n-2; i >= 0; i--) {
            max_price_to_end[i] = Math.max(prices[i], max_price_to_end[i+1]);
            max_profit_to_end[i] = Math.max(max_price_to_end[i] - prices[i], max_profit_to_end[i+1]);
        }
        int max_1 = max_profit_from_start[n-1];
        int max_2 = 0;
        for (int i = 1; i < n-1; i++) {
            max_2 = Math.max(max_2, max_profit_from_start[i] + max_profit_to_end[i]);
        }
        return Math.max(max_1, max_2);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值