LeetCode 123. Best Time to Buy and Sell Stock III(动态规划)

题目来源:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

问题描述

123. Best Time to Buy and Sell Stock III

Hard

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

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

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

Example 1:

Input: [3,3,5,0,0,3,1,4]

Output: 6

Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.

             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

Example 2:

Input: [1,2,3,4,5]

Output: 4

Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.

             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are

             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]

Output: 0

Explanation: In this case, no transaction is done, i.e. max profit = 0.

------------------------------------------------------------

题意

给定一个数组prices表示若干个时段股票的价格,允许最多2次买卖,允许一个时段既卖出又买入,求最大获利。

------------------------------------------------------------

思路

动态规划。

这个问题可以推广为“允许最多k次买卖的最大获利”。

dp[i,t]表示[0:t]时段最多i次买卖的最大获利,有递推式:

dp[i,t]     = max(dp[i, t-1], max(dp[i-1, j] + prices[t] – prices[j], j=0,1,…,t-1))

             = max(dp[i, t-1], prices[t] + inter[t])

inter[t] = max(dp[i-1, j] – prices[j], j=0,1,…,t-1) = max(inter[t-1], dp[i-1, t-1]-prices[t-1])

其中inter[t]是中间表达式,表示dp[i-1,j]-prices[j]当j从0~t-1取值时的最大值。在循环过程中可以根据递推式同时求出dp[i,t]和inter[t].

由于dp[i, ]只依赖dp[i-1, ],所以可以消去“k次买卖这一维度”,用一维dp数组代替二维dp数组。

------------------------------------------------------------

代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.size() <= 1) {
            return 0;
        }
        return kTrans(prices, 2);
    }

private:
    /**
    * max profit under at most k transactions
    */
    int kTrans(vector<int>& prices, int k) {
        int n = prices.size(), i = 0, t = 0, tmp = 0, inter = 0, ans = 0;
        vector<int> dp(n, 0);
        for (i=1; i<=k; i++) {
            inter = dp[0] - prices[0];
            for (t=1; t<n; t++) {
                tmp = dp[t];
                dp[t] = dp[t-1]>(inter+prices[t])? dp[t-1]:(inter+prices[t]);
                inter = (tmp-prices[t])>inter? (tmp-prices[t]):inter;
            }
            ans = dp[n-1]>ans? dp[n-1]:ans;
        }
        return ans;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值