Taro Logo

Maximum Transactions Without Negative Balance

#5 Most AskedMedium
0 views
Topics:
ArraysGreedy Algorithms

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should be returned if even the first transaction causes the balance to drop below zero?
  2. Can individual transactions themselves be negative values, or are they mixed positive and negative integers representing debits and credits?
  3. Are we required to process the transactions strictly in the given sequential order, or can we choose any subset of transactions to maximize the count?
  4. What is the maximum size of the transaction list and the range of values for the initial balance and transaction amounts?
  5. If multiple sequences of transactions yield the same maximum count, does it matter which specific transactions are included, as long as the count is the same?

Brute Force Solution

Approach

This problem asks for the maximum number of transactions we can accept in order without the running balance ever dropping below zero. We greedily accept every transaction as it arrives and maintain a min-heap of the negative transactions taken. Whenever the balance becomes negative, we discard the largest negative transaction seen so far to restore a valid balance.

Here's how the algorithm would work step-by-step:

  1. Initialize the running balance to zero, a counter for valid transactions to zero, and an empty min-heap for negative amounts.
  2. Iterate through each transaction in the given order.
  3. Add the current transaction value to the running balance and increment the transaction count.
  4. If the transaction is negative, push it onto the min-heap of selected negative transactions.
  5. If the balance falls below zero, pop the smallest (most negative) transaction from the heap, subtract it from the balance, and decrement the count.
  6. Return the final transaction count after processing all transactions.

Code Implementation

import heapq

def max_transactions(transactions):
    # Keep track of the current balance and the min-heap of chosen negative transactions
    current_balance = 0
    negative_heap = []
    count = 0
    
    for amount in transactions:
        current_balance += amount
        count += 1
        # Record any negative transaction we accepted into the heap
        if amount < 0:
            heapq.heappush(negative_heap, amount)
        
        # If the balance drops below zero, undo the most negative transaction taken so far
        if current_balance < 0:
            worst_negative = heapq.heappop(negative_heap)
            current_balance -= worst_negative
            count -= 1
            
    return count

Big(O) Analysis

Time Complexity
O(N log N) – Each of the N transactions is processed once, with heap insertions and deletions taking O(log N) time in the worst case.
Space Complexity
O(N) – The priority queue can store at most all N transactions when every transaction is negative or added.

Optimal Solution

Approach

This problem is solved using a greedy approach with a priority queue. We process each transaction in order while maintaining the running balance and a min-heap of all selected negative amounts. Whenever the balance drops below zero, we greedily discard the transaction that caused the largest loss so far to restore non-negativity with the minimal impact on total count.

Here's how the algorithm would work step-by-step:

  1. Initialize the current balance to zero and an empty min-heap to keep track of negative transactions.
  2. Iterate through the transaction list one by one, adding each amount to the running balance and incrementing the count.
  3. Whenever a transaction is negative, push its value into the min-heap.
  4. Check if the running balance is negative after including the current transaction.
  5. If the balance is negative, remove the smallest value (most negative) from the min-heap, subtract it from the balance, and decrement the count.
  6. Return the total count of accepted transactions once all elements have been processed.

Code Implementation

import heapq

def max_transactions(transactions):
    current_balance = 0
    chosen_negatives = []
    count = 0
    # Process transactions in sequential order
    for amount in transactions:
        current_balance += amount
        count += 1
        # Track negative transactions in a min-heap to allow backtracking
        if amount < 0:
            heapq.heappush(chosen_negatives, amount)
        # If the balance becomes negative, remove the largest negative transaction
        if current_balance < 0:
            current_balance -= heapq.heappop(chosen_negatives)
            count -= 1
    return count

Big(O) Analysis

Time Complexity
O(N log N) – Iterating through the array of length N takes linear time, while each push and pop operation on the min-heap takes O(log N) time in the worst case.
Space Complexity
O(N) – In the worst case, the heap stores up to N negative transaction amounts simultaneously.

Edge Cases

Empty transaction list provided as input
How to Handle:
Return zero immediately since no transactions can be performed.
Initial balance is already zero and the first transaction is negative
How to Handle:
Return zero because the balance drops below zero on the very first step.
All transactions are positive additions to the balance
How to Handle:
Process the entire list and return the total length of the array.
A single large negative transaction that exceeds the initial balance
How to Handle:
Stop processing immediately and return a count of zero completed transactions.
Transactions contain a mix of zeros, which do not alter the balance
How to Handle:
Include zeros in the transaction count since they keep the balance valid and non-negative.
Extremely large array of transactions with massive integer values
How to Handle:
Use standard linear iteration with a running sum to maintain O(N) time complexity and prevent overflow issues.
A valid transaction sequence reduces the balance to exactly zero before continuing
How to Handle:
Allow the zero balance state to persist as long as subsequent transactions do not drop it further below zero.
0/25 completed