Best Time to Buy and Sell Stock

Easy

You are given an array prices where prices[i] is the price of a stock on day i. You want to maximize your profit by choosing a single day to buy and a different day to sell. Return the maximum profit. If no profit is possible, return 0.

Examples

InputOutput
prices = [7,1,5,3,6,4]5
prices = [7,6,4,3,1]0

Python Solution

def max_profit(prices: list[int]) -> int:
    min_price = float("inf")
    max_profit = 0
    for p in prices:
        min_price = min(min_price, p)
        max_profit = max(max_profit, p - min_price)
    return max_profit

JavaScript Solution

function maxProfit(prices) {
  let minPrice = Infinity, maxProfit = 0;
  for (const p of prices) {
    minPrice = Math.min(minPrice, p);
    maxProfit = Math.max(maxProfit, p - minPrice);
  }
  return maxProfit;
}

Step-by-Step Explanation

  1. Track the minimum price seen so far.
  2. At each day, profit = price - min_price. Track the maximum profit.

Complexity Analysis

TimeO(n)
SpaceO(1)

Tags

ArrayDynamic Programming

Related Problems

Related Tools

All Problems