您的位置:首页 > 其它

leetcode—Best Time to Buy and Sell Stock IV

2016-06-29 10:59 218 查看
题目:

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.

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

分析:

该题采用动态规划的方法。

会想到:第i天进行第j次交易的最大收益为①第i-1天进行第j次交易的最大收益②第i-1天进行j-1此交易与第i天进行交易的和 中的较大值。

于是,得到方程:

profit[i][j] = max(profit[i – 1][j], profit[i – 1][j – 1] + diff)


其中,

diff=prices[i]-prices[i-1] 。


然而,这种计算方法存在一些问题:第i天的交易可与之前的交易合为一次交易。这样,j的值就减小了1。

于是,重新规划:

temp[i][j] = max ( profit[i-1][j-1]+max(diff,0),temp[i-1][j]+diff)

profit[i][j] = max(profit[i-1][j],temp[i][j]


练习代码:

class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if ( n <= 1 )   return 0;
if ( k <= 0 )   return 0;
int diff;
vector<vector<int>> profit(n+1,vector<int>(k+1,0));
vector<vector<int>> temp(n+1,vector<int>(k+1,0));

for( int i = 2; i <= n; i++ ){
diff= prices[i-1] - prices[i-2];
for(int j = 1; j <= k; j++ ) {
temp[i][j] = max(profit[i-1][j-1]+max(diff,0), temp[i-1][j]+diff);
profit[i][j] = max(profit[i-1][j],temp[i][j]);
}
}
return profit
[k];
}
};


提交后,一直runtime error

于是,将二维vector降维:用一维向量记录到达第i天时的temp最优解和profit最优解。

class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if ( n <= 1 )   return 0;
if ( k <= 0 )   return 0;
if ( k >= n) {
int res = 0;
for(int i = 1; i < n; i++ ){
if(prices[i] > prices[i-1])
res += prices[i]-prices[i-1];
}
return res;
}
int diff;
vector<int> temp(k+1,0);
vector<int> profit(k+1,0);

for(int i = 2; i <= n; i++ ) {
diff = prices[i-1] - prices[i-2];
profit[0] = 0;
temp[0] = 0;
for(int j = 1; j <= k; j++ ) {
temp[j] = max(profit[j-1],temp[j]+diff);
profit[j] = max(temp[j],profit[j]);
}
}
return profit[k];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: