- Leetcode PHP题解--D109 122. Best T
- leetcode:122. Best Time to Buy a
- [数组]122. Best Time to Buy and Se
- Leetcode122-Best Time to Buy and
- 跟我一起刷leetCode算法题9之Best Time to B
- 121. Best Time to Buy and Sell S
- 【2019-07-30】leetcode(121-130)
- 121. Best Time to Buy and Sell S
- BestTimeToBuyAndSellStock with c
- [2018-11-18] [LeetCode-Week11] 1
最开始股票需要先买后卖
题解:
- 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;
}
网友评论