PIXELBANKv8.2.1
Menu

Best Time to Buy and Sell Stock

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:
  • We start by initializing the minimum price and maximum profit: min_price=7min\_price = 7, max_profit=0max\_profit = 0.
  • We then iterate through the array, updating min_pricemin\_price and max_profitmax\_profit as we find lower prices and higher profits:
    • On the second day, min_price=1min\_price = 1.
    • On the third day, max_profit=51=4max\_profit = 5 - 1 = 4.
    • On the fifth day, max_profit=61=5max\_profit = 6 - 1 = 5.
  • The final output is max_profit=5max\_profit = 5.

Constraints:

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

Test Results

0/0
Run code to see test results.