Check LintCode 1000. Best Time to Buy and Sell Stock with Transaction Fee
class Solution {
public:
/**
* @param prices: a list of integers
* @param fee: a integer
* @return: return a integer
*/
int maxProfit(vector<int> &prices, int fee) {
// write your code here
// 双数组DP思想的再次使用:
// f[i]状态表示: 前i个元素最大收益。stay at i-th element:
//1, sell: f[i] = ? + prices[i - 1] - fee. This ? state needs at i-1 th day, have the stock held. This state is the maxProfit that i-1 th day stock was hold. Denote ? as P[i].
//2, not sell: f[i] = f[i - 1];
// now P状态的转移,情况:
// 1,继续hold P[i] = P[i - 1]
// 2,买入 P[i] = f[i - 1] - prices[i - 1].
//初始: f[0] = 0; P[1] = -prices[0]. P[1] = max(P[0), f[0] - prices[0])。所以P[0] = INT_MIN;
//结果: f[n].
int sizeP = prices.size();
if(sizeP <= 1){
return 0;
}
vector<int> global(sizeP + 1, 0);
vector<int> local(sizeP + 1, 0);
//Initial
global[0] = 0;
local[0] = -prices[0];
for(int i = 1; i <= sizeP; i++){
global[i] = max(global[i - 1], local[i - 1] + prices[i - 1] - fee);
local[i] = max(local[i -1], global[i - 1] - prices[i - 1]);
}
return global[sizeP];
}
};
public:
/**
* @param prices: a list of integers
* @param fee: a integer
* @return: return a integer
*/
int maxProfit(vector<int> &prices, int fee) {
// write your code here
// 双数组DP思想的再次使用:
// f[i]状态表示: 前i个元素最大收益。stay at i-th element:
//1, sell: f[i] = ? + prices[i - 1] - fee. This ? state needs at i-1 th day, have the stock held. This state is the maxProfit that i-1 th day stock was hold. Denote ? as P[i].
//2, not sell: f[i] = f[i - 1];
// now P状态的转移,情况:
// 1,继续hold P[i] = P[i - 1]
// 2,买入 P[i] = f[i - 1] - prices[i - 1].
//初始: f[0] = 0; P[1] = -prices[0]. P[1] = max(P[0), f[0] - prices[0])。所以P[0] = INT_MIN;
//结果: f[n].
int sizeP = prices.size();
if(sizeP <= 1){
return 0;
}
vector<int> global(sizeP + 1, 0);
vector<int> local(sizeP + 1, 0);
//Initial
global[0] = 0;
local[0] = -prices[0];
for(int i = 1; i <= sizeP; i++){
global[i] = max(global[i - 1], local[i - 1] + prices[i - 1] - fee);
local[i] = max(local[i -1], global[i - 1] - prices[i - 1]);
}
return global[sizeP];
}
};
Comments
Post a Comment