123. Best Time to Buy and Sell Stock III(动规的好题)

来源:互联网 发布:mac版cad字体乱码 编辑:程序博客网 时间:2024/06/05 08:41

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

class Solution {public:    int maxProfit(vector<int>& prices) {}};

解答:

这个题目可以直接推广到k transactions的情形:

用f[i][j]表示最多i笔交易下在prices[j]处(不包括prices[j])能取得的最大利润,那么f[i][j]=max(f[i][j-1],p[j]-p[k]+f[i-1][k]),k∈[0,j]

也就是说,在第j天,要么卖掉要么不卖(卖了才会赚钱),如果不卖,f[i][j]和f[i][j-1]一样,如果卖,那么前面一定买过(也就是损失过钱),假设损失的是p[k],这样,在第j天卖掉东西的情况下赚取的利润就是p[j]-p[k]+f[i-1][k],其中f[i-1][k]表示做最多i-1笔交易时在p[k]处取得的利润。

这个式子可以改写成:f[i][j]=max(f[i][j-1],max(f[i-1][k]-p[k])+p[j]),k∈[0,j]

改写的理由是:我们需要对p[j]-p[k]+f[i-1][k]取最大值,p[j]是定值,那么只有让f[i-1][k]-p[k]取最大。

AC代码:

class Solution {public:    int maxProfit(vector<int>& prices) {        int tmp,len=prices.size();        int k=2;        vector<vector<int>>dp(k+1,vector<int>(len,0));        if(len<=1)return 0;        for(int i=1;i<=k;i++){            tmp=dp[i-1][0]-prices[0];            for(int j=1;j<len;j++){                dp[i][j]=max(dp[i][j-1],prices[j]+tmp);                tmp=max(tmp,dp[i-1][j]-prices[j]);            }        }        return dp[k][len-1];    }};



原创粉丝点击