THN Interview Prep

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]

dayIndexdelta from prevcontribute
11-7 = -60
25-1 = +4+4
33-5 = -20
46-3 = +3+3
54-6 = -20

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

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?

On this page