Best Time to Buy and Sell Stock

Advanced

Best Time to Buy and Sell Stock

Imagine you're a time-traveling stock broker! You can go back in time to any day and buy some stocks, and sell them on a future day. Your challenge is to calculate the maximum profit you can get from a list of stock prices.

Given a list of prices where prices[i] is the price of a stock on the i-th day, write a function that returns the maximum profit you can achieve by buying and then selling one share of stock. If no profit is possible, return 0.

For example, let's see how it works:

# Example 1 prices = [7, 1, 5, 3, 6, 4] # You can buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5 max_profit(prices) # returns 5 # Example 2 prices = [7, 6, 4, 3, 1] # In this case, no transactions are done and the max profit is 0 max_profit(prices) # returns 0

Task

Implement the function max_profit(prices: List[int]) -> int: that calculates the maximum profit from buying and selling one stock.

Tips

  • Try iterating through the price list while remembering the lowest price so far and calculate potential profit.
  • Keep track of the maximum profit encountered during the loop.

Have fun and happy trading, young time travelers!

Geek
Inputs

Arg 1:

[7,1,5,3,6,4]
Expected Output
5
Actual Output
Best Time to Buy and Sell Stock [advanced] | Coding for Kids