Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

12 Core Algorithmic Patterns & 168 Practice Problems

  • 1. Two Pointers (9 Paradigms, 32 Problems): Converging pointers, sorted pair sums, container with most water, trapping rain water, 3Sum, plus the Sliding Window and Fast & Slow Pointers paradigms (Floyd cycle detection, monotonic window invariants, longest substrings, minimum window).
  • 2. Binary Search (8 Paradigms, 12 Problems): Monotonic predicate partitioning, boundary searching, rotated arrays, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 8 Problems): Bitmasking, XOR tricks, counting set bits, subset enumeration via bitmasks.
  • 4. Math & Geometry (5 Paradigms, 10 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (8 Paradigms, 17 Problems): Path sums, lowest common ancestor, tree diameter, subtree serialization, validating BSTs.
  • 6. Tree/Graph Breadth-First Search (4 Paradigms, 11 Problems): Level-order traversals, shortest path, rotting oranges, word ladders.
  • 7. Graphs (6 Paradigms, 14 Problems): Topological sort, cycle detection, Dijkstra, bipartite validation, network delay.
  • 8. Backtracking (5 Paradigms, 13 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens.
  • 9. Dynamic Programming (7 Paradigms, 14 Problems): Memoization vs tabulation, knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (8 Paradigms, 10 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (5 Paradigms, 13 Problems): Trie, Union-Find, LRU Cache, LFU Cache, Monotonic Stacks.
  • 12. Intervals & Stack / Miscellaneous (7 Paradigms, 14 Problems): Merge intervals, daily temperatures, largest rectangle in histogram, trapping rain water via stack.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Multi-language Rosetta Stone contrasting abstract invariants with concrete solutions across Python, C#, Java, TypeScript, C++, Go, and Rust.
  2. Stage 2 (Active Recall): Reconstruct algorithmic template invariants from memory with real-time feedback before looking at solutions.
  3. Stage 3 (Senior SWE AI Mock Coach): Simulated senior mock interview evaluating Big-O space/time tradeoffs, edge cases, and code reviews in Monaco Editor.
  4. Stage 4 (Solve on Your Own): Timed sandbox challenges verified against automated test suites in Python, C#, Java, and TypeScript.

Equipped with SM-2 Spaced Repetition Review Hub, Studio Cockpit workspace layout, and interactive study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Compute Coins: 40 free coins upon signup, +20 daily login bonus, +25 referral bonus.
  • 24-Hour AI Coaching Pass: 5 compute coins unlocks unlimited senior SWE AI coaching for a full 24 hours.
  • BYOK (Bring Your Own Key): Completely free unlimited AI coaching if using your own Gemini/OpenAI API key.
  • Refund & Subscription Policy: No recurring charges, no subscription traps, and no paid paywalls. Free tier provides full learning path.
  • Platform Operator: Hi👋WebEnterprise Inc. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

180Items
Theory Context•Dynamic Programming
MediumLC 122

Best Time to Buy and Sell Stock II (LeetCode 122)

You will see how two running states, owning a share or not, capture every buy-and-sell plan in one pass.

Target Frequency:AmazonBloombergMicrosoft

You get an integer array prices: on day i, one share of a stock costs prices[i]. On each day you may buy a share, sell the share you own, or both, but you can never own more than one share at a time. Selling and then buying again on the same day is allowed, and there is no limit on the number of trades.

Return the largest total profit you can make. If no trade helps, the answer is 0.

Worked Examples

Example 1
Input:prices = [7,1,5,3,6,4]
Output:7
701152336445buysellbuysell
Explanation: Buy on day 1 at `1` and sell on day 2 at `5` for `+4`, then buy on day 3 at `3` and sell on day 4 at `6` for `+3`. Total `7`.
Example 2
Input:prices = [1,2,3,4,5]
Output:4
1021324354buysell
Explanation: Buy on day 0 at `1` and sell on day 4 at `5` for `+4`. Selling and buying back every day adds up to the same `4`.
Example 3
Input:prices = [7,6,4,3,1]
Output:0
7061423314
Explanation: The price only falls, so every trade loses money. Never buying keeps the profit at `0`.

⚖️Formal Constraints & Bounds

  • 1 <= prices.length <= 3 * 104

  • 0 <= prices[i] <= 104

Deep-Dive & Conceptual Insights

Why It Works & Core Invariant

Only two facts matter at the end of a day: whether you own a share, and the best profit for each case. Each day's two values come from yesterday's two, so one pass finds the best plan.

Real-World Scenario & Production Applications

Any system that moves between a few modes step by step, and pays or earns on each switch: a battery that charges or discharges against hourly power prices, a machine that runs or idles, a position that is open or closed. Keeping the best value for each mode finds the best plan in one pass.

Step-by-Step Execution Trace Table

Day iphold = max(hold, cash - p)cash = max(cash, hold + p)What the states mean
07-7 (start)0 (start)Bought on day 0 / own nothing
11max(-7, 0 - 1) = -1max(0, -7 + 1) = 0Buying at 1 beats keeping the share bought at 7
25max(-1, 0 - 5) = -1max(0, -1 + 5) = 4Selling at 5 locks in +4
33max(-1, 4 - 3) = 1max(4, -1 + 3) = 4Buy again at 3 with the 4 in hand
46max(1, 4 - 6) = 1max(4, 1 + 6) = 7Selling at 6 adds +3
54max(1, 7 - 4) = 3max(7, 1 + 4) = 7Nothing beats 7; return cash = 7
Scroll horizontally to see all columns, or expand to full screen
Core Invariant Specification & Code Shape
Archetype Code Shape
Python
1At the end of each day you either own one share (`hold`) or none (`cash`): keep the best profit for each state.
2`hold = max(hold, cash - p)` keeps the share or buys today; `cash = max(cash, hold + p)` stays out or sells today. Both read yesterday's values.
3Start `hold = -prices[0]` and `cash = 0`, update both once for every later day with one tuple assignment, then `return cash`.
4The trap: `hold` starts at `-prices[0]`, not `0`, or `cash` sells a share you never paid for.

Target: Best Time to Buy and Sell Stock II (LeetCode 122). Owning a share on day 0 means we paid prices[0] for it. Starting at 0 would be a free share that cash could sell.

Boundary Model: Topologically Ordered Subproblem Recurrence (DAG(Directed Acyclic Graph))

Optimal substructure: DP state dp[i] depends strictly on already-computed subproblems. Rolling array reduces space from O(S) to O(1 tier).

Loop Invariant Termination

Iterate base cases -> compute states in topological transition order (dp[i] = min/max/sum of transitions).

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

A trading plan looks like a huge search: on every day you could buy, sell or wait, so there are exponentially many plans. State Machine DP collapses it. At the end of any day you are in exactly one of two states: you own a share (hold) or you don't (cash). Tomorrow's best profit in each state depends only on today's two numbers, never on how you got there. So you carry two numbers through the array and update them once per day.

🏟️ The Analogy: A Light Switch With a Price Tag

Picture a switch that is either on (you own a share) or off (you don't). Each day the switch can stay where it is for free, or flip: flipping on costs today's price, flipping off pays today's price. You don't need to remember the whole history of flips; you only need the best balance you could have right now with the switch on, and the best balance with it off.

🪄 The Mathematical Harmony / Magic Trick
Code / Blueprint
hold = -prices[0] # switch on day 0: we paid for the share
cash = 0 # switch off: nothing spent
for i in range(1, len(prices)):
p = prices[i]
hold, cash = max(hold, cash - p), max(cash, hold + p)
return cash
 

The tuple assignment evaluates both right-hand sides with yesterday's hold and cash before either changes. Every legal plan is a path of switch flips, and each max keeps only the best way to arrive at a state, so the final cash is the best plan of all.

💡 Summary

Name the states, write one line per allowed move, update from yesterday's values, and start from a state you can actually be in (hold = -prices[0]). Extra rules (a fee, a cooldown, a trade limit) become an extra term or an extra state, not a new algorithm. One pass: O(N)O(N)O(N) time, O(1)O(1)O(1) space.

  • Starting hold at 0: hold = 0 means owning a share you never paid for, so on day 1 cash = max(0, 0 + p) sells it for a free profit. On [7,1,5,3,6,4] that returns 8 instead of 7. Start with hold = -prices[0].

  • Reading a value that already changed today: the tuple assignment hold, cash = max(hold, cash - p), max(cash, hold + p) computes both right-hand sides from yesterday's values. In this problem two separate lines happen to give the same answer, but with a fee or a cooldown they don't, so build the habit here.

  • Returning max(hold, cash): holding a share at the end means money was spent on something never sold; cash is always at least as large, so return cash.

  • Treating it as "one best trade": that is Best Time to Buy and Sell Stock (LC 121). Here trades are unlimited, so every profitable rise can be taken, and the state machine takes them all automatically.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

You will see how a senior engineer spots a two-state machine behind a trading question and defends it out loud.

Pattern Recognition Signals

The 10-second spot

"Buy and sell as many times as you like" and "own at most one share at a time": at the end of every day you are in one of two modes (own a share or not), and each day's choices depend only on that mode. A few modes with day-by-day moves between them is the signal for State Machine DP.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

After each day, hold is the best profit so far while owning one share and cash the best profit so far while owning none: hold = max(hold, cash - p) (keep or buy) and cash = max(cash, hold + p) (keep or sell), both reading yesterday's values.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • hold = -prices[0], not 0: starting at 0 means owning a share for free, and cash then sells it (on [7,1,5,3,6,4] the answer comes out 8 instead of 7).

  • Read yesterday's values: hold, cash = max(hold, cash - p), max(cash, hold + p) evaluates both right-hand sides before assigning. Here the order happens not to matter, but with a cooldown or a fee, two separate lines read a value that already changed today.

  • return cash, not max(hold, cash): ending the last day with a share never beats selling it or never buying it.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd solve this with State Machine DP. At the end of any day I'm in one of two states: I own a share, or I don't. I keep the best profit for each, hold and cash. Each new price allows two moves: hold becomes the better of keeping my share or buying today out of cash, and cash becomes the better of staying out or selling today out of hold. I compute both from yesterday's values in one tuple assignment. It's correct because every legal plan of trades is a path through these two states, and each update keeps the best way to reach each state. The trap is the start: hold must be minus the first price, not zero, or I'd sell a share I never paid for. At the end I return cash, since ending with a share is never better. One pass, so O(N) time and O(1) space.

So: name the states hold and cash, write one line per move, start hold at -prices[0], and return cash.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the code: after setting hold and cash, the loop for i in range(1, len(prices)) runs once for each of the other N - 1 days, and its body reads one price and does one tuple assignment with two max calls, a constant amount of work. Total: O(N).

SPACE COMPLEXITY

O(1)

The code keeps only hold, cash, i and p, whatever the input size, and returns one integer: O(1) extra space.

Formal Recurrence Relation

T(N) = O(1) + (N - 1) · O(1) = O(N)

Look at the code: after setting hold and cash, the loop for i in range(1, len(prices)) runs once for each of the other N - 1 days, and its body reads one price and does one tuple assignment with two max calls, a constant amount of work. Total: O(N).

Derivation Progression

Start states

O(1)

hold = -prices[0] and cash = 0 are two assignments.

Daily loop

(N - 1) iterations

for i in range(1, len(prices)) visits every day after day 0 exactly once.

Per-day update

O(1) per iteration

One tuple assignment with two max calls, whatever N is.

Total

O(N)

Constant work per day over N days.

Variable Definitions

NNN

Number of days, len(prices)

ppp

Today's price, prices[i]

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative, no recursion

🔵 Auxiliary Heap

O(1): hold, cash, i, p

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N): every day is visited even when prices only fall

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N)

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "trade as many times as you like", "never own more than one share". Every day ends in one of two modes, owning a share or not, and the next day's options depend only on the mode: State Machine DP with states hold and cash.

CONSTRAINTS & BOUNDS

N≤3×104N \le 3 \times 10^4N≤3×104 days, prices ≤104\le 10^4≤104. The profit is at most the sum of all rises, below 3×1083 \times 10^83×108, so it fits a 32-bit integer. Budget: O(N)O(N)O(N) time, O(1)O(1)O(1) space; the loop also works on a live price stream, since it keeps no history.

FAANG PRODUCTION TRAPS & EDGE CASES

Starting hold at 0 creates a free share. In a streaming service, the state is only two numbers, but it must be updated once per price in order: replaying or reordering ticks changes the answer, so process each tick exactly once.

Core Algorithmic State Invariants

1. Two-State Invariant

After each day, `hold` is the best profit so far while owning one share and `cash` the best profit so far while owning none. No other fact about the past can change a future decision.

2. Yesterday-Only Transition

`hold = max(hold, cash - p)` and `cash = max(cash, hold + p)` both read yesterday's values (one tuple assignment). Every legal plan is a path through the two states, and each `max` keeps the best way to arrive.

3. Real Start, Linear Pass

The start must be a state you can really be in: `hold = -prices[0]`, `cash = 0`. One O(1) update per day gives O(N) time and O(1) space, and the answer is the final `cash`.

Theory Context•Dynamic Programming
MediumLC 122

Best Time to Buy and Sell Stock II (LeetCode 122)

You will see how two running states, owning a share or not, capture every buy-and-sell plan in one pass.

Target Frequency:AmazonBloombergMicrosoft

You get an integer array prices: on day i, one share of a stock costs prices[i]. On each day you may buy a share, sell the share you own, or both, but you can never own more than one share at a time. Selling and then buying again on the same day is allowed, and there is no limit on the number of trades.

Return the largest total profit you can make. If no trade helps, the answer is 0.

Worked Examples

Example 1
Input:prices = [7,1,5,3,6,4]
Output:7
701152336445buysellbuysell
Explanation: Buy on day 1 at `1` and sell on day 2 at `5` for `+4`, then buy on day 3 at `3` and sell on day 4 at `6` for `+3`. Total `7`.
Example 2
Input:prices = [1,2,3,4,5]
Output:4
1021324354buysell
Explanation: Buy on day 0 at `1` and sell on day 4 at `5` for `+4`. Selling and buying back every day adds up to the same `4`.
Example 3
Input:prices = [7,6,4,3,1]
Output:0
7061423314
Explanation: The price only falls, so every trade loses money. Never buying keeps the profit at `0`.

⚖️Formal Constraints & Bounds

  • 1 <= prices.length <= 3 * 104

  • 0 <= prices[i] <= 104

Deep-Dive & Conceptual Insights

Why It Works & Core Invariant

Only two facts matter at the end of a day: whether you own a share, and the best profit for each case. Each day's two values come from yesterday's two, so one pass finds the best plan.

Real-World Scenario & Production Applications

Any system that moves between a few modes step by step, and pays or earns on each switch: a battery that charges or discharges against hourly power prices, a machine that runs or idles, a position that is open or closed. Keeping the best value for each mode finds the best plan in one pass.

Step-by-Step Execution Trace Table

Day iphold = max(hold, cash - p)cash = max(cash, hold + p)What the states mean
07-7 (start)0 (start)Bought on day 0 / own nothing
11max(-7, 0 - 1) = -1max(0, -7 + 1) = 0Buying at 1 beats keeping the share bought at 7
25max(-1, 0 - 5) = -1max(0, -1 + 5) = 4Selling at 5 locks in +4
33max(-1, 4 - 3) = 1max(4, -1 + 3) = 4Buy again at 3 with the 4 in hand
46max(1, 4 - 6) = 1max(4, 1 + 6) = 7Selling at 6 adds +3
54max(1, 7 - 4) = 3max(7, 1 + 4) = 7Nothing beats 7; return cash = 7
Scroll horizontally to see all columns, or expand to full screen
Core Invariant Specification & Code Shape
Archetype Code Shape
Python
1At the end of each day you either own one share (`hold`) or none (`cash`): keep the best profit for each state.
2`hold = max(hold, cash - p)` keeps the share or buys today; `cash = max(cash, hold + p)` stays out or sells today. Both read yesterday's values.
3Start `hold = -prices[0]` and `cash = 0`, update both once for every later day with one tuple assignment, then `return cash`.
4The trap: `hold` starts at `-prices[0]`, not `0`, or `cash` sells a share you never paid for.

Target: Best Time to Buy and Sell Stock II (LeetCode 122). Owning a share on day 0 means we paid prices[0] for it. Starting at 0 would be a free share that cash could sell.

Boundary Model: Topologically Ordered Subproblem Recurrence (DAG(Directed Acyclic Graph))

Optimal substructure: DP state dp[i] depends strictly on already-computed subproblems. Rolling array reduces space from O(S) to O(1 tier).

Loop Invariant Termination

Iterate base cases -> compute states in topological transition order (dp[i] = min/max/sum of transitions).

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

A trading plan looks like a huge search: on every day you could buy, sell or wait, so there are exponentially many plans. State Machine DP collapses it. At the end of any day you are in exactly one of two states: you own a share (hold) or you don't (cash). Tomorrow's best profit in each state depends only on today's two numbers, never on how you got there. So you carry two numbers through the array and update them once per day.

🏟️ The Analogy: A Light Switch With a Price Tag

Picture a switch that is either on (you own a share) or off (you don't). Each day the switch can stay where it is for free, or flip: flipping on costs today's price, flipping off pays today's price. You don't need to remember the whole history of flips; you only need the best balance you could have right now with the switch on, and the best balance with it off.

🪄 The Mathematical Harmony / Magic Trick
Code / Blueprint
hold = -prices[0] # switch on day 0: we paid for the share
cash = 0 # switch off: nothing spent
for i in range(1, len(prices)):
p = prices[i]
hold, cash = max(hold, cash - p), max(cash, hold + p)
return cash
 

The tuple assignment evaluates both right-hand sides with yesterday's hold and cash before either changes. Every legal plan is a path of switch flips, and each max keeps only the best way to arrive at a state, so the final cash is the best plan of all.

💡 Summary

Name the states, write one line per allowed move, update from yesterday's values, and start from a state you can actually be in (hold = -prices[0]). Extra rules (a fee, a cooldown, a trade limit) become an extra term or an extra state, not a new algorithm. One pass: O(N)O(N)O(N) time, O(1)O(1)O(1) space.

  • Starting hold at 0: hold = 0 means owning a share you never paid for, so on day 1 cash = max(0, 0 + p) sells it for a free profit. On [7,1,5,3,6,4] that returns 8 instead of 7. Start with hold = -prices[0].

  • Reading a value that already changed today: the tuple assignment hold, cash = max(hold, cash - p), max(cash, hold + p) computes both right-hand sides from yesterday's values. In this problem two separate lines happen to give the same answer, but with a fee or a cooldown they don't, so build the habit here.

  • Returning max(hold, cash): holding a share at the end means money was spent on something never sold; cash is always at least as large, so return cash.

  • Treating it as "one best trade": that is Best Time to Buy and Sell Stock (LC 121). Here trades are unlimited, so every profitable rise can be taken, and the state machine takes them all automatically.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

You will see how a senior engineer spots a two-state machine behind a trading question and defends it out loud.

Pattern Recognition Signals

The 10-second spot

"Buy and sell as many times as you like" and "own at most one share at a time": at the end of every day you are in one of two modes (own a share or not), and each day's choices depend only on that mode. A few modes with day-by-day moves between them is the signal for State Machine DP.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

After each day, hold is the best profit so far while owning one share and cash the best profit so far while owning none: hold = max(hold, cash - p) (keep or buy) and cash = max(cash, hold + p) (keep or sell), both reading yesterday's values.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • hold = -prices[0], not 0: starting at 0 means owning a share for free, and cash then sells it (on [7,1,5,3,6,4] the answer comes out 8 instead of 7).

  • Read yesterday's values: hold, cash = max(hold, cash - p), max(cash, hold + p) evaluates both right-hand sides before assigning. Here the order happens not to matter, but with a cooldown or a fee, two separate lines read a value that already changed today.

  • return cash, not max(hold, cash): ending the last day with a share never beats selling it or never buying it.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd solve this with State Machine DP. At the end of any day I'm in one of two states: I own a share, or I don't. I keep the best profit for each, hold and cash. Each new price allows two moves: hold becomes the better of keeping my share or buying today out of cash, and cash becomes the better of staying out or selling today out of hold. I compute both from yesterday's values in one tuple assignment. It's correct because every legal plan of trades is a path through these two states, and each update keeps the best way to reach each state. The trap is the start: hold must be minus the first price, not zero, or I'd sell a share I never paid for. At the end I return cash, since ending with a share is never better. One pass, so O(N) time and O(1) space.

So: name the states hold and cash, write one line per move, start hold at -prices[0], and return cash.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the code: after setting hold and cash, the loop for i in range(1, len(prices)) runs once for each of the other N - 1 days, and its body reads one price and does one tuple assignment with two max calls, a constant amount of work. Total: O(N).

SPACE COMPLEXITY

O(1)

The code keeps only hold, cash, i and p, whatever the input size, and returns one integer: O(1) extra space.

Formal Recurrence Relation

T(N) = O(1) + (N - 1) · O(1) = O(N)

Look at the code: after setting hold and cash, the loop for i in range(1, len(prices)) runs once for each of the other N - 1 days, and its body reads one price and does one tuple assignment with two max calls, a constant amount of work. Total: O(N).

Derivation Progression

Start states

O(1)

hold = -prices[0] and cash = 0 are two assignments.

Daily loop

(N - 1) iterations

for i in range(1, len(prices)) visits every day after day 0 exactly once.

Per-day update

O(1) per iteration

One tuple assignment with two max calls, whatever N is.

Total

O(N)

Constant work per day over N days.

Variable Definitions

NNN

Number of days, len(prices)

ppp

Today's price, prices[i]

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative, no recursion

🔵 Auxiliary Heap

O(1): hold, cash, i, p

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N): every day is visited even when prices only fall

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N)

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "trade as many times as you like", "never own more than one share". Every day ends in one of two modes, owning a share or not, and the next day's options depend only on the mode: State Machine DP with states hold and cash.

CONSTRAINTS & BOUNDS

N≤3×104N \le 3 \times 10^4N≤3×104 days, prices ≤104\le 10^4≤104. The profit is at most the sum of all rises, below 3×1083 \times 10^83×108, so it fits a 32-bit integer. Budget: O(N)O(N)O(N) time, O(1)O(1)O(1) space; the loop also works on a live price stream, since it keeps no history.

FAANG PRODUCTION TRAPS & EDGE CASES

Starting hold at 0 creates a free share. In a streaming service, the state is only two numbers, but it must be updated once per price in order: replaying or reordering ticks changes the answer, so process each tick exactly once.

Core Algorithmic State Invariants

1. Two-State Invariant

After each day, `hold` is the best profit so far while owning one share and `cash` the best profit so far while owning none. No other fact about the past can change a future decision.

2. Yesterday-Only Transition

`hold = max(hold, cash - p)` and `cash = max(cash, hold + p)` both read yesterday's values (one tuple assignment). Every legal plan is a path through the two states, and each `max` keeps the best way to arrive.

3. Real Start, Linear Pass

The start must be a state you can really be in: `hold = -prices[0]`, `cash = 0`. One O(1) update per day gives O(N) time and O(1) space, and the answer is the final `cash`.

Rosetta Dual-Monaco Comparison
Python 3
CANONICAL INVARIANT TEMPLATE
Loading...
CONCRETE: BEST TIME TO BUY AND SELL STOCK II (LEETCODE 122)
T = O(N)S = O(1)
Loading...
Pattern Implementation Mapping TableCanonical Invariant ⟷ Concrete Code ⟷ Engineering Rationale
Canonical InvariantConcrete CodeEngineering Rationale
Start in a state you can really be in: bought on day 0hold = -prices[0]Owning a share on day 0 means we paid prices[0] for it. Starting at 0 would be a free share that cash could sell.
Start the no-share state with nothing spentcash = 0Not buying at all is always allowed, so the best no-share profit starts at 0 and never drops below it.
Visit each later day oncefor i in range(1, len(prices)): p = prices[i]Day 0 is already in the start values; every other day gets exactly one update.
One line per allowed move, all reading yesterday's stateshold, cash = max(hold, cash - p), max(cash, hold + p)hold keeps its share or buys from cash; cash stays out or sells from hold. The tuple assignment reads both old values before changing either.
Answer from the final no-share statereturn cashEnding the last day still owning a share is never better than having sold it or never bought it.
© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•