Visualize

Pattern visualizer

Stock Buy and Sell (Multiple Transactions)

With unlimited trades there is no decision to agonise over. Any profitable run from a low day to a high day pays exactly the sum of the day-to-day rises inside it, because selling and immediately rebuying at the same price costs nothing. So the whole problem collapses to one sweep: add every positive difference between consecutive days and ignore every negative one. No running minimum, no lookahead, no dynamic programming — a fall simply cannot be worth holding through, since you are free to sell before it. Animated on: prices = [4,2,6,5,9,9,1,7] — buy and sell as many times as you like (never holding two lots at once) for the maximum total profit..

Greedy: bank every upward step

time O(n)space O(1)step 1 / 9
4
[0]
2
[1]
6
[2]
5
[3]
9
[4]
9
[5]
1
[6]
7
[7]
line 2

Unlimited trades means the days are independent: any profitable run from a low to a high equals the sum of its day-to-day rises, so there is nothing to plan ahead for. profit starts at 0 and every upward step gets banked on its own.

Pseudocode
1FUNCTION maxProfit(prices)
2 profit <- 0
3 FOR i <- 1 TO LENGTH(prices) - 1
4 IF prices[i] > prices[i - 1]
5 profit <- profit + prices[i] - prices[i - 1]
6 RETURN profit

← / → step · space play · Home restart

Where to practice Arrays