Best Time to Buy And Sell Stock

EasySliding WindowFree to try
Asked byAmazonFacebookMicrosoftBloombergGoogleGoldman Sachs

Problem

Given an array where prices[i] is the price of a stock on day i, choose a single day to buy and a later day to sell to maximize your profit, and return the maximum profit achievable. Return 0 if no profit is possible.

Examples

Example 1
Input:prices = [7,1,5,3,6,4]
Output:5
Buy on day 2 (price 1), sell on day 5 (price 6).
Example 2
Input:prices = [7,6,4,3,1]
Output:0
Prices only fall, so no profit is possible.

Constraints

  • 1 <= prices.length <= 10^5

Try it now — no sign-up needed. Write your solution in Python or JavaScript, run it against test cases, and submit for a verdict, right in your browser.

Open the editor →

How to approach it: the Sliding Window pattern

A window — a contiguous subarray or substring — expands and shrinks as it moves across the input, so you track a running condition instead of recomputing it from scratch for every possible window.

Look for this pattern when

  • The problem asks for the longest/shortest/best contiguous subarray or substring meeting a condition.
  • Brute force would recompute a sum or count for every possible window — a sign that work can be shared between overlapping ranges.

Read the full Sliding Window guide →

Video walkthroughs

Original problem on LeetCode ↗

More Sliding Window problems