难度:中等。
标签:动态规划。
正确解法:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n <= 1)return 0;
int right_max = prices[n - 1];
int res = right_max - prices[n - 2];
for(int i = n - 3; i >= 0; --i){
right_max = max(right_max, prices[i + 1]);
res = max(res, right_max - prices[i]);
}
return res < 0?0:res;
}
};
结果: