122. Best Time to Buy and Sell Stock II ¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14class 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; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13class 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; } } 1 2 3 4 5 6 7 8 9 10class 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