best_time_to_buy_and_sell_stock

 1# @leet start
 2class Solution:
 3    def maxProfit(self, prices: list[int]) -> int:
 4        """
 5        The best buy/sell pair is determined by the minimum price that comes before
 6        the largest price.
 7        We keep track of the minimum price we've seen so far, and the max profit,
 8        which is curr - min_so_far.
 9        Finally, we return the maximum profit after we've applied it to the entire array.
10        """
11        min_so_far = prices[0]
12        max_profit_so_far = 0
13
14        for price in prices[1:]:
15            min_so_far = min(min_so_far, price)
16            max_profit_so_far = max(max_profit_so_far, price - min_so_far)
17
18        return max_profit_so_far
19
20
21# @leet end
22s = Solution()
23
24
25def test():
26    assert s.maxProfit([7, 1, 5, 3, 6, 4]) == 5
27    assert s.maxProfit([7, 6, 5, 4, 3, 2, 1]) == 0
class Solution:
 3class Solution:
 4    def maxProfit(self, prices: list[int]) -> int:
 5        """
 6        The best buy/sell pair is determined by the minimum price that comes before
 7        the largest price.
 8        We keep track of the minimum price we've seen so far, and the max profit,
 9        which is curr - min_so_far.
10        Finally, we return the maximum profit after we've applied it to the entire array.
11        """
12        min_so_far = prices[0]
13        max_profit_so_far = 0
14
15        for price in prices[1:]:
16            min_so_far = min(min_so_far, price)
17            max_profit_so_far = max(max_profit_so_far, price - min_so_far)
18
19        return max_profit_so_far
def maxProfit(self, prices: list[int]) -> int:
 4    def maxProfit(self, prices: list[int]) -> int:
 5        """
 6        The best buy/sell pair is determined by the minimum price that comes before
 7        the largest price.
 8        We keep track of the minimum price we've seen so far, and the max profit,
 9        which is curr - min_so_far.
10        Finally, we return the maximum profit after we've applied it to the entire array.
11        """
12        min_so_far = prices[0]
13        max_profit_so_far = 0
14
15        for price in prices[1:]:
16            min_so_far = min(min_so_far, price)
17            max_profit_so_far = max(max_profit_so_far, price - min_so_far)
18
19        return max_profit_so_far

The best buy/sell pair is determined by the minimum price that comes before the largest price. We keep track of the minimum price we've seen so far, and the max profit, which is curr - min_so_far. Finally, we return the maximum profit after we've applied it to the entire array.

s = <Solution object>
def test():
26def test():
27    assert s.maxProfit([7, 1, 5, 3, 6, 4]) == 5
28    assert s.maxProfit([7, 6, 5, 4, 3, 2, 1]) == 0