注意:
一定要明确转移方程
解法:动态规划
思想:
●状态定义:
●转移方程:
前i日的最大利润 = max(前i - 1日的最大利润, 第i日价格 - 前i日最低价格)
dp[i] = max(dp[i - 1], prices[i] - min(prices[0 : i])),前i日最低价格用一个变量来维护
我的理解:
前i天的最大利润要么就是第i天不操作,即前i - 1天最大利润。
要么就是第i天操作即卖出
●初始状态:
dp[0] = 0,即首日利润为0
●返回值:
dp[n - 1]
复杂度:
●时间:O(n)
●空间:O(n),可优化至O(1)
未优化代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int count_day = prices.size();
if(count_day < 2)
return 0;
vector<int>dp(count_day, 0);
//前i日最低价格
int min_price = prices[0];
for(int i = 1; i < count_day; ++i){
min_price = min(min_price, prices[i]);
dp[i] = max(dp[i - 1], prices[i] - min_price);
}
return dp[count_day - 1];
}
};
优化代码(优化空间,dp[i]只与dp[i - 1]有关):
class Solution {
public:
int maxProfit(vector<int>& prices) {
int count_day = prices.size();
if(count_day < 2)
return 0;
int pre_profit = 0, cur_profit = 0;
int min_price = prices[0];
for(int i = 1; i < count_day; ++i){
min_price = min(min_price, prices[i]);
cur_profit = max(pre_profit, prices[i] - min_price);
pre_profit = cur_profit;
}
return cur_profit;
}
};