Bank app~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-122dp
A bank app lets customers trade units of a savings fund. The price of a unit is known for each day. A customer holds at most one unit at a time, and may buy or sell once a day.
The fund charges a fee for every night a unit is held. A customer who buys on one day and sells on a later day pays the fee for each night in between. The customer wants the best total profit over any number of trades.
Write best_profit(prices, daily_cost).
prices[i] is the price of one unit on day i.daily_cost. A unit bought on day i and sold on day j costs (j - i) × daily_cost.0 when no trade pays.Input: prices = [3,8,2,6,4,9], daily_cost = 1
Output: 11The solution keeps two numbers for the end of each day. The first is the best profit when holding nothing. The second is the best profit when holding one unit.
| Day | Price | Best profit holding nothing | Best profit holding one |
|---|---|---|---|
| 0 | 3 | 0 | -3 |
| 1 | 8 | 4 | -4 |
| 2 | 2 | 4 | 2 |
| 3 | 6 | 7 | 1 |
| 4 | 4 | 7 | 3 |
| 5 | 9 | 11 | 2 |
The answer is the last number in the first column. The trades are 3 to 8, 2 to 6 and 4 to 9, each over one night.
Input: prices = [3,8,2,6,4,9], daily_cost = 0
Output: 14With no fee, every rise is collected: 5 + 4 + 5.
Input: prices = [5,4,3], daily_cost = 0
Output: 0The price only falls, so no trade pays.
1 ≤ len(prices) ≤ 100,0000 ≤ prices[i] ≤ 1,000,0000 ≤ daily_cost ≤ 1,000,000Each day you can wait, buy or sell, so the number of plans doubles every day. For 60 days that is over a quintillion plans. But a day only needs to know whether you hold a unit, so two numbers for each day are enough.