Best Time to Buy and Sell Stock II
Problem Statement
You are given prices, where prices[i] is the price of one share on day i. On each day you may buy one share, sell the share you hold, or do nothing.
You can hold at most one share at any time. You may trade as many times as you like. You may also sell and buy again on the same day, as long as you never hold two shares.
Return the largest profit you can make.
An integer array prices.
The largest total profit from any number of buys and sells.
Buy at 1 (index 1) and sell at 5 (index 2): profit 4. Then buy at 3 (index 3) and sell at 6 (index 4): profit 3. The total is 4 + 3 = 7.
Buy at 1 and sell at 5 for 4. Trading every day gives the same total, because 1 + 1 + 1 + 1 = 4.
The price only falls, so the best choice is to never buy.
- • 1 ≤ prices.length ≤ 3 × 10^4
- • 0 ≤ prices[i] ≤ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
On each day, try every allowed action; no memory
Cache each (day, holding) pair so it is solved only once
Keep the best cash and best hold values; update both once per day
Ask one question per day: am I holding a share or not? From the answer, try each allowed action (buy, sell, or nothing) and let the recursion handle the rest of the days. Keep the best total.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like DP — Kadane / Subarray translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.