You are given an array prices of length N, where prices[i] is the predicted price of a stock on day i. Each day you may perform exactly one of the following actions:
-
Buy one share of the stock.
-
Sell any number of the shares you currently hold (at least one share).
-
Do nothing.
You may hold any number of shares at a time, but you can buy at most one share per day. At the end of day N - 1 you must hold zero shares. Return the maximum profit you can achieve.
Function Signature
def max_profit(prices: list[int]) -> int:
Rules
-
You start with zero shares and have unlimited cash, so a buy is always possible. Profit is the total received from sales minus the total paid for purchases.
-
A sale happens at that day's price and can sell anywhere from one share to every share you hold.
-
A day on which you sell cannot also be a day on which you buy.
-
Doing nothing on every day is a valid plan, so the answer is never negative.
Constraints
-
1 <= len(prices) <= 10^5
-
0 <= prices[i] <= 10^9
Examples
Input: prices = [5, 3, 2]
Output: 0
Prices fall every day, so any share bought would be sold at a loss. Doing nothing on all three days gives 0.
Input: prices = [1, 2, 100]
Output: 197
Buy one share on day 0 at price 1 and one on day 1 at price 2, then sell both on day 2 at price 100. The profit is (100 - 1) + (100 - 2) = 197.
Input: prices = [1, 3, 1, 2]
Output: 3
Buy on day 0 and sell on day 1 for a gain of 2, then buy on day 2 and sell on day 3 for a gain of 1. Holding the first share until day 3 would earn only 1 on it, so selling at the day 1 peak is better.