Skip to main content

Maximum Transactions Without Negative Balance - Solution & Explanation

MediumPremiumFree on FleetCodeArrayGreedyHeap (Priority Queue)8 min readAsked at: Paytm
Practice this problem

Problem Statement

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.

 

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 <= 105
  • -109 <= transactions[i] <= 109

Approach Overview

Problem Overview: You are given a list of transactions that either add to or subtract from your balance. You can choose which transactions to execute, but the running balance must never drop below zero. The goal is to perform the maximum number of transactions while maintaining a non‑negative balance at every step.

Approach 1: Brute Force Subset Exploration (Exponential Time)

The most direct idea is to try every subset of transactions and check whether executing them in order keeps the balance non‑negative. For each subset, iterate through the chosen transactions, maintain a running balance, and discard the subset if the balance ever drops below zero. Track the largest valid subset size. This approach explores 2^n possibilities and performs an O(n) validation for each subset, giving O(n * 2^n) time and O(n) space for recursion. It quickly becomes infeasible once the input size grows, but it clarifies the constraint that the prefix sum must always stay ≥ 0.

Approach 2: Greedy + Heap / Ordered Set (O(n log n))

A greedy strategy works because negative transactions are the only ones that risk breaking the balance constraint. Iterate through the array and maintain a running balance. Every transaction is tentatively accepted. When the transaction value is negative, store it in a max structure (such as a max‑heap or ordered set) so you can quickly remove the most damaging one later.

If the running balance becomes negative, remove the transaction with the largest negative impact from the chosen set. This is done by extracting the smallest value (largest loss) from the heap and adding it back to the balance. Removing the worst transaction restores the balance while minimizing the number of removals. Continue processing the rest of the transactions.

This works because keeping smaller losses instead of larger ones maximizes how many transactions you can afford overall. Each transaction is processed once, and heap operations cost O(log n). The total complexity is O(n log n) time and O(n) space. The approach combines ideas from Greedy decision making with a Heap (Priority Queue) to efficiently track the worst negative transaction.

Since the input is simply processed sequentially, the algorithm also naturally fits problems modeled with Array traversal and prefix balance tracking.

Recommended for interviews: The Greedy + Heap solution is what interviewers expect. Brute force demonstrates understanding of the prefix constraint but does not scale. Recognizing that you only need to discard the worst negative transaction when the balance breaks shows strong algorithmic intuition and leads to the optimal O(n log n) implementation.

Solution

We use an ordered set (such as C++'s multiset, Java's TreeMap, Python's SortedList) to store the selected transaction amounts, and maintain a variable s to record the current balance. Initially s=0, and the answer ans is initialized to the number of transactions.

Then we traverse each transaction amount x:

  1. Add x to the balance s and add x to the ordered set.
  2. If the balance s becomes negative at this point, it means some negative amounts among the currently selected transaction amounts have caused insufficient balance. To retain as many transactions as possible, we should remove the smallest amount among the currently selected transaction amounts (because removing the smallest amount can maximize the balance). We remove the smallest amount y from the ordered set, subtract y from the balance s, and decrement the answer ans by 1.
  3. Repeat step 2 until the balance s is no longer negative.

After traversal is complete, the answer ans is the maximum number of transactions that can be performed.

The time complexity is O(n times log n), where n is the number of transactions. The space complexity is O(n).

Code

Python

Java

C++

Go

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Subset ExplorationO(n * 2^n)O(n)Useful only for understanding the constraint or verifying small inputs
Greedy + Heap (Priority Queue)O(n log n)O(n)General optimal solution; efficiently removes the worst negative transaction when balance becomes negative
Greedy + Ordered SetO(n log n)O(n)Alternative implementation when language libraries provide ordered sets or balanced BST structures

Video Solution

leetcode 3711 Practice of Heap - Maximum Transactions Without Negative Balance | heapCode-Yao62 views views

Frequently Asked Questions

Is Maximum Transactions Without Negative Balance easy or hard?
The problem is typically classified as Medium difficulty. The main challenge is recognizing the greedy insight: when the balance becomes negative, removing the worst negative transaction maximizes how many total transactions remain feasible.
Maximum Transactions Without Negative Balance Python/Java solution
Most implementations use a max‑heap (or simulate one using a min‑heap with negated values). The algorithm iterates through the array, updates the balance, pushes negative transactions into the heap, and removes the largest loss whenever the balance drops below zero. The same logic works in Python, Java, C++, and Go using their standard priority queue libraries.
How to solve Maximum Transactions Without Negative Balance in O(n log n)?
Traverse the transactions while maintaining a running balance. Push every negative transaction into a max‑heap. If the balance becomes negative, remove the largest negative value from the heap and add it back to the balance. This greedy removal keeps the balance valid while maximizing the total number of accepted transactions.
What is the best approach for Maximum Transactions Without Negative Balance?
The best approach uses a greedy strategy with a heap (priority queue). Iterate through transactions while maintaining a running balance and store negative transactions in a max structure. If the balance becomes negative, remove the transaction with the largest loss. This ensures the maximum number of transactions while keeping the balance non‑negative, with O(n log n) time complexity.
Is Maximum Transactions Without Negative Balance asked at Google/Amazon/Meta?
Problems using greedy selection with heaps and prefix balance constraints frequently appear in interviews at companies like Amazon, Google, and Meta. Variations of this pattern show up in scheduling, resource allocation, and prefix‑sum constraint problems.
What data structure is used in Maximum Transactions Without Negative Balance?
The key data structure is a heap (priority queue) or an ordered set. It stores negative transactions so the algorithm can quickly remove the one with the largest negative impact when the running balance becomes invalid.
What is the time complexity of Maximum Transactions Without Negative Balance?
The optimal solution runs in O(n log n) time. Each transaction is processed once, and negative transactions may be inserted or removed from a heap, which costs O(log n) per operation. Space complexity is O(n) to store the selected negative transactions.

Ready to solve this problem?

Practice Maximum Transactions Without Negative Balance with our built-in code editor and test cases.

Practice on FleetCode