◀ THE GRIND — ARRAYS & HASHING

Best Time to Buy And Sell Stock II

MEDIUM✓ CHIP-TIMEDLC #122 — FULL STATEMENT ↗

The drill: Maximize total profit from a price series when you can buy and sell as many times as you like, one share at a time, never holding more than one share at once.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A series of daily stock prices arrives, and the task is to walk away with the maximum total profit possible — buying and selling as many separate times as you like.

Only one share can be held at any moment: a share has to be sold before another one is bought, so overlapping holdings are never allowed.

There's no penalty or cost attached to each individual transaction, so chaining together many small trades is exactly as free as making one long one.

EX 01
prices = [7, 1, 5, 3, 6, 4]
7
TWO SEPARATE RISES: 1→5 AND 3→6
EX 02
prices = [1, 2, 3, 4, 5]
4
ONE LONG STEADY CLIMB
EX 03
prices = [7, 6, 4, 3, 1]
0
STRICTLY FALLING, NO PROFIT POSSIBLE
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Trying every possible combination of buy and sell days finds the answer, but the number of combinations explodes with every extra day. What does holding a share on day i actually depend on?

HINT 2 THE STRUCTURE

Since a full round trip is always allowed between any two days, ask a smaller question: is tomorrow's price higher than today's? Every such rise is profit you're allowed to bank.

HINT 3 ONE STEP FROM THE ANSWER

Sum up every positive difference between consecutive days — buy the moment before each rise, sell right after it. Chaining every small rise together matches any longer single trade you could have made instead.

COACH'S BOARD — THE PATTERN, STEP BY STEP
BANK EVERY RISEPATTERN · GREEDY, CAPTURE EVERY RISEprices = [7, 1, 5, 3, 6, 4]
7
1
5
3
6
4
RUNNING PROFIT
profit0
STEP 1

prices = [7, 1, 5, 3, 6, 4]. Sum every positive day-to-day rise — that equals the max profit with unlimited trades.

STEP 1 / 8 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/best-time-to-buy-and-sell-stock-ii.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i - 1]:
                profit += prices[i] - prices[i - 1]
        return profit
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 7 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED