LeetCode Solutions
122. Best Time to Buy and Sell Stock II
Time: $O(n)$ Space: $O(1)$
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sell = 0;
int hold = INT_MIN;
for (const int price : prices) {
sell = max(sell, hold + price);
hold = max(hold, sell - price);
}
return sell;
}
};
class Solution {
public int maxProfit(int[] prices) {
int sell = 0;
int hold = Integer.MIN_VALUE;
for (final int price : prices) {
sell = Math.max(sell, hold + price);
hold = Math.max(hold, sell - price);
}
return sell;
}
}
class Solution:
def maxProfit(self, prices: List[int]) -> int:
sell = 0
hold = -math.inf
for price in prices:
sell = max(sell, hold + price)
hold = max(hold, sell - price)
return sell