all entries
A-015Day 152026.05.17easyleetcode #121neetcode150

Best Time to Buy and Sell Stock

#array#dynamic-programming
leetcode #121 · best-time-to-buy-and-sell-stock
01

Problem

· problem
P.015

Best Time to Buy and Sell Stock

leetcode #121

You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

constraints
  • · 1 ≤ prices.length ≤ 10⁵
  • · 0 ≤ prices[i] ≤ 10⁴
// paraphrased summary — see source for full text
examples
example 1input → output
[7,1,5,3,6,4]
5
example 2input → output
[7,6,4,3,1]
0
02

Pre-solve

· pre-solve
● 1list shown● 2select● 3reveal
  • Can we buy and sell on the same day?
  • Must we complete a transaction?
  • Can we complete multiple buy-sell transactions?
  • If all prices are strictly decreasing, what should we return?
  • Can we use future prices to decide whether to buy?
  • What if the array has only one element?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03

Logic Structure

· logic
● 1slots shown● 2pick per slot● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Initialize result variable
res = 0
res = float('-inf')
res = prices[0]
step 2· Initialize minimum price
lowest = prices[0]
lowest = float('inf')
lowest = 0
step 3· Iterate through array
for price in prices:
for i in range(1, len(prices)):
for price in prices[1:]:
step 4· Check for new minimumnested
if price < lowest:
if price <= lowest:
if price > lowest:
step 5· Update minimum price│ │ nested
lowest = price
min_price = price
lowest = price - res
step 6· Calculate and update maximum profitnested
res = max(res, price - lowest)
res = price - lowest
res = max(res, lowest - price)
step 7· Return result
return res
return lowest
return max(res, lowest)
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04

Solve · Trace

· solve
solution.py
1
class Solution:
2
    def maxProfit(self, prices: List[int]) -> int:
3
        res = 0
4
        
5
        lowest = prices[0]
6
        for price in prices:
7
            if price < lowest:
8
                lowest = price
9
            res = max(res, price - lowest)
10
        return res
mental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[7,1,5,3,6,4]
5
case 2
[7,6,4,3,1]
0
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.