Problem Overview
"Best Time to Buy and Sell Stock II" (LeetCode #122) involves maximizing profit from stock prices over multiple days, allowing unlimited buy/sell transactions with the constraint of holding at most one share at a time. You receive an array prices where prices[i] is the price on day i.[1][7]
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.[6][7][1]
prices.length ≤ 3 × 10⁴prices[i] ≤ 10⁴[7][6][1]| Input | Output | Explanation |
|-------|--------|-------------|
| [7,1,5,3,6,4] | 7 | Buy day 2 (1), sell day 3 (5) → +4; buy day 4 (3), sell day 5 (6) → +3. Total: 7. [1] |
| [1,2,3,4,5] | 4 | Buy day 1 (1), sell day 5 (5) or accumulate daily: +1+1+1+1=4. [1] |
| [7,6,4,3,1] | 0 | No profitable transactions possible. [1] |
| [] or [1] | 0 | Insufficient days for transactions. [1] |
The greedy solution sums all positive differences between consecutive days, capturing every uphill segment.[6][1]