题目
题解
- 动态规划
动态规划 前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}
代码
// class Solution {
// public:
// int maxProfit(vector<int>& prices) {
// int res=0;
// for(int i=0;i<prices.size()-1;i++){
// for(int j=i+1;j<prices.size();j++){
// res=max(res,prices[j]-prices[i]);
// }
// }
// return res;
// }
// };
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==1)
return 0;
int res=prices[1]-prices[0];
int k=res>0?0:1;
for(int i=2;i<prices.size();i++){
if(prices[i]-prices[k]>0)
res=max(res,prices[i]-prices[k]);
else
k=i;
}
return res>0?res:0;
}
};