All DSA problems
EasyArraysAmazonMicrosoftBloomberg
Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a stock on day i.
You want to maximize profit by choosing a single day to buy and a different future day to sell.
Print the maximum profit. If no profit is possible, print 0.
**Input format**
First line: n
Second line: n integers (prices)
Examples
Example 1
Input:
6 7 1 5 3 6 4
Output: 5
Buy on day 2 (price=1), sell on day 5 (price=6), profit=5
Example 2
Input:
5 7 6 4 3 1
Output: 0
Prices only fall → profit 0
Constraints
- 1 ≤ n ≤ 10^5
- 0 ≤ prices[i] ≤ 10^4
Target: O(n) time · O(1) space