121. Best Time to Buy and Sell Stock ¶ 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 sellOne = 0; int holdOne = INT_MIN; for (const int price : prices) { sellOne = max(sellOne, holdOne + price); holdOne = max(holdOne, -price); } return sellOne; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13class Solution { public int maxProfit(int[] prices) { int sellOne = 0; int holdOne = Integer.MIN_VALUE; for (final int price : prices) { sellOne = Math.max(sellOne, holdOne + price); holdOne = Math.max(holdOne, -price); } return sellOne; } } 1 2 3 4 5 6 7 8 9 10class Solution: def maxProfit(self, prices: list[int]) -> int: sellOne = 0 holdOne = -math.inf for price in prices: sellOne = max(sellOne, holdOne + price) holdOne = max(holdOne, -price) return sellOne