You are given an integer array trades representing the profit or loss of a sequence of trades in chronological order. A positive value is a profit and a negative value is a loss.
For tax purposes, losses from previous sales can be used to offset future profits. Specifically, you maintain a running loss carry-over balance (initially 0). For each trade processed in order:
-
If the trade is a loss (negative), add its magnitude to the loss carry-over balance.
-
If the trade is a profit (positive), use as much of the loss carry-over as possible to offset it. The taxable profit for that trade is the remaining profit after offsetting, and the carry-over balance is reduced accordingly.
-
If the trade is
0
, nothing changes.
Return the total taxable profit after processing all trades in order.
Function Signature
def total_taxable_profit(trades: list[int]) -> int:
Rules
-
A loss offsets only profits that come after it in the list. A profit earlier in the list stays fully taxable.
-
Carry-over left after the last trade does not change the answer.
-
The total can reach about
10^14
, which is beyond the 32-bit range. Return it as a Python
int
.
Constraints
-
1 <= len(trades) <= 10^5
-
-10^9 <= trades[i] <= 10^9
Examples
Input: trades = [100, -50, 200, -30, 80]
Output: 300
The first 100 is fully taxable. The 50 loss offsets part of the 200 (150 taxable) and the 30 loss offsets part of the 80 (50 taxable), so the total is 100 + 150 + 50 = 300.
Input: trades = [-100, -50, 200, 300]
Output: 350
The two losses build a carry-over of 150. The 200 profit uses all of it and leaves 50 taxable, and the 300 profit is fully taxable, for 350 in total.
Input: trades = [50, -200, 0, 120]
Output: 50
The 50 comes before any loss, so it stays taxable. The 200 loss covers the whole 120 profit, and the 80 of carry-over that remains is never used.