Best Time to Buy and Sell Stock III - LeetCode 123

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).

Hide Tags
  Array Dynamic Programming




分析:
最多买卖两次,那就把元素组分成两段,分别求出两段的最大利益,然后相加,于是得到动态规划解法(类似于求出数组中除去自身元素外的其他所有元素的乘积):
先从前往后,求出第0天到第i天买卖一次能获得的最大利益,记入forward[i];
再从后往前,求出第i天到n-1 天买卖一次能获得的最大利益,记入backward[i];
然后两次买卖的最大利益 max_profi = max{forward[i] + backward[i]},其中i取值[0,n-1]

12ms//
class Solution {
public:
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    int maxProfit(vector<int> &prices) {
        // write your code here
        int n = prices.size();
        if(n < 2)
            return 0;
        if( n == 2)
            return prices[1]> prices[0]? prices[1] - prices[0]:0;
        vector<int> forward(n,0); //forward[i]表示从第0天到第i天买卖一次能获得的最大利益
        vector<int> backward(n,0); //backward[i]表示从第i天到n-1天买卖一次能获得的最大利益
         
        int min_p = prices[0];
        for(int i = 1; i < n; i++){  //从前往后计算forward 
            if(prices[i] < min_p)
                min_p = prices[i];
            int t = prices[i] - min_p;
            forward[i] =  max(t,forward[i-1]);
        }
        
        int max_p = prices[n-1];
        for(int i = n-2; i >= 0; i--){  //从后往前计算backward
            if(prices[i] > max_p)
                max_p = prices[i];
            int t =  max_p - prices[i];
            backward[i] = max(t,backward[i+1]);
        }
        
        int max_profi = 0;  
        for(int i = 0; i < n - 1; i++){ //求出两段和最大值
            int t = forward[i] + backward[i];
            max_profi = max(max_profi , t);
        }
        
        return max_profi;
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值