
原本以为是一个很难想的动态规划,没想到是最简单的贪心......
如果实在想不出就画个折线图,只买上涨的就行了,所有上涨的段都取到。
真的没想到会这么简单......
cpp
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit=0;
for(int i=1;i<prices.size();i++){
if(prices[i]>prices[i-1]) profit+=prices[i]-prices[i-1];
}
return profit;
}
};
另外看到答案的动态规划很聪明,记录手头有和没有股票的钱,每经过一天有四种选择,买、不买、卖、不卖,根据观察这一天的股票情况决定。
cpp
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit[30001][2];
profit[0][0]=0;
profit[0][1]=-prices[0];
for(int i=1;i<prices.size();i++){
profit[i][0]=max(profit[i-1][0],profit[i-1][1]+prices[i]);
profit[i][1]=max(profit[i-1][1],profit[i-1][0]-prices[i]);
cout<<i<<" "<<profit[i][0]<<" "<<profit[i][1]<<endl;
}
return profit[prices.size()-1][0];
}
};