您的位置:首页 > 其它

188. Best Time to Buy and Sell Stock IV

2016-06-28 09:25 281 查看

Problem

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 k transactions.

Note:

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

Solution

采用动态规划来解决问题。

我们需要维护如下两个量:

local[i][j]:当前到达第i天最多可以进行j次交易 ,而且最后一次交易在第i天卖出,所得到的最大利润。

global[i][j]:当前到达第i天最多可以进行j次交易,所得到的最大利润。

状态转移方程:

global[i][j] = max(local[i][j], global[i-1][j])

上述方程比较两个量的大小:①当前局部最大值;②过往全局最大值

local[i][j] = max(global[i-1][j-1] + max(diff, 0), local[i-1][j] + diff)

上述方程比较两个量的大小:

①全局到i-1天进行j-1次交易,然后加上今天的交易(如果今天的交易赚钱的话)。

②取局部第i-1天进行j次交易,然后加上今天的差值(local[i-1][j]是第i-1天卖出的交易,它加上diff后变成第i天卖出,并不会增加交易次数。无论diff是正还是负都要加上,否则就不满足local[i][j]必须在最后一天卖出的条件了)

另外需要注意的一个问题是,当k远大于数组的大小时,上述算法将变得低效。因此将其改用不限交易次数的方式解决

class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if(n<2)
return 0;
if(k >=n)
return maxProfit2(prices);
vector<vector<int>> local(n,vector<int>(k+1,0));
vector<vector<int>> global(n,vector<int>(k+1,0));

for(int i = 1;i<n;++i)
{
int diff = prices[i] - prices[i-1];
for(int j = 1;j<=k;++j)
{
local[i][j] = max(global[i - 1][j - 1], local[i - 1][j] + diff);
global[i][j] = max(global[i - 1][j], local[i][j]);
}
}

return global[n-1][k];
}
private:
int maxProfit2(vector<int>& prices)
{
int maxProfit = 0;
int n = prices.size();
for(int i = 1;i<n;++i)
{
int diff = prices[i] - prices[i-1];
if(diff > 0)
maxProfit+=diff;
}

return maxProfit;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: