[LeetCode] Maximum Transactions Without Negative Balance

3711. Maximum Transactions Without Negative Balance

You are given an integer array transactions, where transactions[i] represents the amount of the ith 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int maxTransactions(vector<int>& transactions) {
long long skip = 0, balance = 0;
priority_queue<int, vector<int>, greater<>> q;
for(auto& t : transactions) {
if(t < 0) q.push(t);
balance += t;
if(balance < 0) {
skip++;
balance -= q.top(); q.pop();
}
}

return transactions.size() - skip;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2025/11/21/PS/LeetCode/maximum-transactions-without-negative-balance-description/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.