122. Best Time to Buy and Sell Stock II
At a Glance
- Topic: arrays-hashing
- Pattern: Greedy (accumulate positive daily deltas)
- Difficulty: Medium
- Companies: Amazon, Meta, Google, Microsoft, Bloomberg
- Frequency: High
- LeetCode: 122
Problem (one-liner)
Given prices for each day, you may complete as many buy–sell transactions as you like (must sell before buying again), but each day you hold at most one share. Return maximum total profit.
Recognition Cues
- "Unlimited transactions", "may buy and sell same day multiple times conceptually"
- Every upward step contributes — sum positive consecutive differences
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — enumerate transaction sequences — exponential.
- Better — DP with states for hold/cash —
O(n)time /O(n)space. - Optimal — greedy: add
max(0, prices[day]-prices[day-1])—O(n)time /O(1)space.
Optimal Solution
Go
package main
func maxProfit(prices []int) int {
total := 0
for dayIndex := 1; dayIndex < len(prices); dayIndex++ {
delta := prices[dayIndex] - prices[dayIndex-1]
if delta > 0 {
total += delta
}
}
return total
}JavaScript
function maxProfit(prices) {
let total = 0;
for (let dayIndex = 1; dayIndex < prices.length; dayIndex++) {
const delta = prices[dayIndex] - prices[dayIndex - 1];
if (delta > 0) {
total += delta;
}
}
return total;
}Walkthrough
prices = [7,1,5,3,6,4]
| dayIndex | delta from prev | contribute |
|---|---|---|
| 1 | 1-7 = -6 | 0 |
| 2 | 5-1 = +4 | +4 |
| 3 | 3-5 = -2 | 0 |
| 4 | 6-3 = +3 | +3 |
| 5 | 4-6 = -2 | 0 |
Total 7.
Edge Cases
- Flat prices — zero profit.
- Strictly increasing — sum all gaps.
- Length 0 or 1 — zero.
Pitfalls
- Confusing with exactly one transaction (121).
- Thinking you must track separate buys — greedy peaks capture optimal.
Similar Problems
- 121. Best Time to Buy and Sell Stock — single transaction version.
- 053. Maximum Subarray — adjacent deltas relate to sum structure.
- 189. Rotate Array — unrelated practice on price arrays as sequences.
Variants
- Transaction fee per trade — greedy adjusted or DP.
- Stock III — at most two transactions.
Mind-Map Tags
#greedy #arrays #stock #adjacent-delta #accumulation
Last updated on
Spotted something unclear or wrong on this page?