ExamAdda Logo

Best Time to Buy and Sell Stock

Easy

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and a different future day to sell that stock.

Return the maximum profit you can achieve.

If no profit can be made, return 0.

Example 1

Input

6
7 1 5 3 6 4

Output

5

Explanation

Buy on day 2 at price 1 and sell on day 5 at price 6.

Profit = 6 − 1 = 5, which is the maximum possible.

Example 2

Input

5
7 6 4 3 1

Output

0

Explanation

The stock price decreases every day, so no profitable transaction is possible.

Return 0.

Constraints

1 ≤ prices.length ≤ 10⁵
0 ≤ prices[i] ≤ 10⁴

Hints:

Hint 1

Keep track of the minimum stock price seen so far while traversing the array.

Hint 2

At each day, calculate the profit by selling on that day. Update the maximum profit whenever you find a better one.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 1, 2026

Last updated

Aug 1, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output