Talentd
FleetCode

3711. Maximum Transactions Without Negative Balance

Medium46.1% acceptance1 companyPremium elsewhere, free here

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

Asked at 1 company

Hints open one at a time

Hint 1
Scan the list left to right, keeping a running balance and a container accepted that tracks the sizes of negative transactions you have taken.
Hint 2
Always take nonnegative transactions; they increase balance and the total count.
Hint 3
If a negative t can be paid (balance + t >= 0), accept it and record its absolute value in accepted.
Hint 4
If a negative would make the balance go below zero, but you previously accepted a larger negative, replace that larger one with the current smaller one (restore balance, swap in the smaller): this trade increases the number of transactions you can keep.
14:30
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[2,-5,3,-1,-2]
Input
[-1,-2,-3]
Input
[3,-2,3,-2,1,-1]
Your code is saved on this device.Solution