v9.1.1
Menu

Best Time to Buy and Sell Stock

easyFREESliding WindowBlind 75

Given an array prices where prices[i] is the price of a given stock on the i-th day, find the maximum profit you can achieve by buying on one day and selling on a later day.

If no profit is possible, return 0.

Example

Input
7,1,5,3,6,4
Output
5
Reasoning
  • The input prices lists one price per day: day 1 is 77, day 2 is 11, then 5,3,6,45, 3, 6, 4 on days 3 to 6.
  • A trade is a pair of days i<ji < j: buy at pip_i, sell at pjp_j, profit pj−pip_j - p_i. The output is the largest such profit, or 00 if every pair loses money.
  • Buying on day 1 at 77 never pays: every later price is lower, so all those profits are negative.
  • Buying on day 2 at 11 is far better. Selling on days 3, 4, 5, 6 gives 5−1=45-1=4, 3−1=23-1=2, 6−1=56-1=5, 4−1=34-1=3. The best is 55 (sell on day 5 at 66).
  • Every other buy day starts higher than 11 (buy at 33 and sell at 66 gives only 33), so the answer is 5.
  • Notice that 7−1=67 - 1 = 6 is not allowed: the 77 comes before the 11, and you cannot sell before you buy. If prices only ever fall, no pair profits, so the answer is 0.

Constraints

  • 1 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^4

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.