01
02
03
04
05
06
07
08
09
10
11
A
A2Z Sheet

81. Stock Buy and Sell & The Time-Travel Trader

Medium
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)

  1. Track minPrice = Infinity and maxProfit = 0.
  2. Iterate through prices day by day:
  3. If prices[i] < minPrice, update minPrice = prices[i].
  4. Else if prices[i] - minPrice > maxProfit, update maxProfit = prices[i] - minPrice.
  5. Return maxProfit.

### 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
14px
Ln 1:Col 1
8 lines•119 chars
Spaces: 2•UTF-8
JS(Node v20.12)