Step 3: Solve Problems on Arrays [Easy -> Medium -> Hard]›Medium
Stock Buy and Sell & The Time-Travel Trader
MediumFunction: stockBuyAndSell()
ASCI Mission Breakdown • Simple as Hell
"Find the single best day to buy and future day to sell for maximum profit."
Real-World Metaphor:
Imagine tracking a vintage trading card. You remember the cheapest garage-sale price you ever saw it for. Every time you see it again in the future, you calculate how much money you would have made if you bought it back at that bargain price.
Interactive Visual WalkthroughARRAY-POINTERS
Step 1 / 2
Prices: [7, 1, 5, 3, 6, 4]
7
[0]
Buy Day
1
[1]
5
[2]
3
[3]
6
[4]
4
[5]
Memory Notepad / State Tracker
minPrice:1
maxProfit:0
Evaluating
1. Day 1: Bargain Buy at Price 1
Price drops to 1. Record bargain price: minPrice = 1.
How to Think About This (Mental Model)
Track minPrice = Infinity and maxProfit = 0.
Iterate through prices day by day:
If prices[i] < minPrice, update minPrice = prices[i].
### The Mission
You are given an array `prices` where `prices[i]` is the price of a given stock on the `i`-th day.
You want to maximize your profit by choosing **one single day** to buy the stock and choosing a **different day in the future** to sell it. Return the maximum profit you can achieve. If you cannot achieve any profit, return **0**.
Examples
Example 1
Input: nums = [1,2,3,4,5]
Output: [1,2,3,4,5]
Constraints
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
Topic Tags:
Solve Problems on Arrays [Easy -> Medium -> Hard]MediumstockBuyAndSell