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
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.
1FUNCTION maxProfit(prices)2 profit <- 03 FOR i <- 1 TO LENGTH(prices) - 14 IF prices[i] > prices[i - 1]5 profit <- profit + prices[i] - prices[i - 1]6 RETURN profit
← / → step · space play · Home restart