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.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


这题要结合121,122题来一起思考。这一题和121的要求差不多,但是最多只能进行两次的操作,就最多可以买入卖出两次,同时必须先买入才能卖出,然后问最大利润是多少。这一题用贪心就做不了了,需要用到动态规划,其中设f[i]表示区间[0,i]之间的最大利润,设g[i]表示区间[i,n-1]之间的最大利润。所以结果就是max{f[i] + g[i]},用三个循环就可以解决,那么时间和空间复杂度是O(n),代码如下。

Code(LeetCode运行9ms):

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if (n < 2) {
            return 0;
        }
        
        vector<int> f(n, 0); //f[i]表示[0,i]的最大利润.
        vector<int> g(n, 0); //g[i]表示[i, n-1]的最大利润
        
        for (int i = 1, Min = prices[0]; i < n; i++) {
            Min = min(Min, prices[i]);
            f[i] = max(f[i - 1], prices[i] - Min);
        }
        
        for (int i = n - 2, Max = prices[n - 1]; i >= 0; i--) {
            Max = max(Max, prices[i]);
            g[i] = max(g[i - 1], Max - prices[i]);
        }
        
        int result = 0;
        for (int i = 0; i < n; i++) {
            result = max(result, f[i] + g[i]);
        }
        return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值