Best Time to Buy and Sell Stock
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 your profit by choosing a single day to buy and a single day to sell (you must buy before you sell). Return the maximum profit you can achieve from this transaction. If no profit is possible, return 0. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=6, prices=[7 1 5 3 6 4] → 5 (buy at 1, sell at 6)
Input format — only if your code reads from stdin
Input format (stdin): - First line: integer n (number of days) - Second line: n space-separated integers (prices) Output: a single integer — the maximum profit.
Approach
One pass: track the minimum price seen so far (minPrice). For each day, compute profit = prices[i] - minPrice and update the global maximum. Update minPrice whenever a lower price is seen.
Input
Output
- •
1 ≤ n ≤ 10^5, 0 ≤ prices[i] ≤ 10^4
More Arrays problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards