笨方法,算出了所有的递增序列,当时没有想到贪心
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0)
return 0;
int money = 0;
int pos = 0, pre = 0, cur = 1;
while(cur < prices.size()){
if(prices[pre] < prices[cur]){
pre++;
cur++;
}else{
if(pre != pos){
money += prices[pre] - prices[pos];
pos = cur;
pre = cur;
cur++;
}else{
pos++;
pre++;
cur++;
}
}
}
if(pos != prices.size() - 1){
money += prices[prices.size() - 1] - prices[pos];
}
return money;
}
};
贪心
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0, n = prices.size();
for (int i = 0; i < n - 1; ++i) {
if (prices[i] < prices[i + 1]) {
res += prices[i + 1] - prices[i];
}
}
return res;
}
};
其实时间差不多,都是一遍for循环