[LeetCode] Best Time to Buy and Sell Stock II

122. Best Time to Buy and Sell Stock II

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

  • new solution update 2022.02.07
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maxProfit(vector<int>& p) {
int res = 0;
for(int buy = 0; buy < p.size();) {
int sell = buy + 1;
for(; sell < p.size() and p[sell] >= p[sell - 1]; sell++) {}
res += max(0, p[sell] - p[buy]);
buy = sell;
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res(0), sz(prices.size()), p(0);
bool buy = false;
for(int i = 0; i < sz - 1; i++) {
if(prices[i] < prices[i + 1] && !buy) {
p = prices[i]; buy ^= buy;
} else if(prices[i] > prices[i + 1] && buy) {
res += prices[i] - p;
p = buy = 0;
}
}

return buy ? res + prices.back() - p : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/13/PS/LeetCode/best-time-to-buy-and-sell-stock-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.