Maximum Transactions Without Negative Balance Problem
Description
LeetCode Problem 3711.
You are given an integer array transactions, where transactions[i] represents the amount of the i^th transaction:
- A positive value means money is received.
- A negative value means money is sent.
The account starts with a balance of 0, and the balance must never become negative. Transactions must be considered in the given order, but you are allowed to skip some transactions.
Return an integer denoting the maximum number of transactions that can be performed without the balance ever going negative.
Example 1:
Input: transactions = [2,-5,3,-1,-2]
Output: 4
Explanation:
One optimal sequence is [2, 3, -1, -2], balance: 0 → 2 → 5 → 4 → 2.
Example 2:
Input: transactions = [-1,-2,-3]
Output: 0
Explanation:
All transactions are negative. Including any would make the balance negative.
Example 3:
Input: transactions = [3,-2,3,-2,1,-1]
Output: 6
Explanation:
All transactions can be taken in order, balance: 0 → 3 → 1 → 4 → 2 → 3 → 2.
Constraints:
1 <= transactions.length <= 10^5-10^9 <= transactions[i] <= 10^9
Solution
Approach: Greedy + Min-Heap
Take every transaction in order and keep the amounts chosen so far in a min-heap, together with the running balance s. The answer starts at the number of transactions.
For each amount x, add it to s and push it into the heap. If s drops below zero, the cheapest way to repair it is to drop the smallest chosen amount y (the most negative one): pop it, set s -= y, and decrement the answer. Repeat until s is non-negative again. Whatever remains in the heap is the largest set of transactions that never overdraws the account.
Complexity: O(n log n) time and O(n) space.
from heapq import heappush, heappop
class Solution:
def maxTransactions(self, transactions: List[int]) -> int:
h = []
s = 0
ans = len(transactions)
for x in transactions:
s += x
heappush(h, x)
while s < 0:
s -= heappop(h)
ans -= 1
return ans