122. Best Time to Buy and Sell S
2017-11-23 本文已影响13人
乘瓠散人
最开始股票需要先买后卖
题解:
- suppose the first sequence is "a <= b <= c <= d", the profit is "d - a = (b - a) + (c - b) + (d - c)";
- suppose another one is "a <= b >= b' <= c <= d", the profit is not difficult to be figured out as "(b - a) + (d - b')";
所以只需要考虑递增序列
AC代码:
public:
int maxProfit(vector<int>& prices) {
int sum =0;
for(int i=1; i<prices.size(); i++){
if(prices[i] > prices[i-1]){
sum += prices[i] - prices[i-1];
}
}
return sum;
}
RE代码:
public:
int maxProfit(vector<int>& prices) {
int sum =0;
for(int i=0; i<prices.size()-1; i++){
if(prices[i] < prices[i+1]){
sum += prices[i+1] - prices[i];
}
}
return sum;
}