Back to DSA sheet
Best Time to Buy and Sell Stock
EasyArraysYou are given the daily prices of a stock. Pick one day to buy and a later day to sell so that the profit (sell price minus buy price) is as large as possible. If no profitable transaction is possible, the answer is 0.
Input format (stdin): the first line has n. The second line has n prices. Output the maximum profit.
Examples
Input: 6
7 1 5 3 6 4
Output: 5
Buy at 1 (day 2) and sell at 6 (day 5) for a profit of 5.
Input: 5
7 6 4 3 1
Output: 0
Prices only fall, so the best choice is to make no transaction.
Constraints
- 1 <= n <= 10^5
- 0 <= prices[i] <= 10^4
Sheets
Blind 75Grind 75NeetCode 150NeetCode 250Striver A2Z
best-time-to-buy-and-sell-stock.cpp3 sample tests
Loading editor
Test results
Run the sample tests to check your solution against expected output.
Custom input (stdin)
Output
Run your code to see its output.