Ctrl K

A Balance for Any Order

Hard
You are given a list operations, where operations[i] = [cost, refund]. Every operation must be run exactly once, but the order is not known in advance. To start an operation, the account must hold at least cost. Afterwards the balance changes by - cost + refund: the cost is charged first, then refund is paid back. Return the smallest starting balance that guarantees all operations can be run **no matter which order** they come in.
Example 1
operations=[[6, 2], [3, 5], [4, 0]] → 11

The losing operations [6, 2] and [4, 0] eat 4 + 4 = 8 in total. Running them first and putting [3, 5] last requires 8 + 3 = 11 at that moment, and no order is worse, so the answer is 11.

Example 2
operations=[[0, 7], [5, 5]] → 5

No operation lowers the balance, so it is enough to afford the most expensive one: 5.

Example 3
operations=[[2, 0], [2, 0], [2, 0]] → 6
Constraints
  • 1 ≤ len(operations) ≤ 10⁵
  • operations[i] = [cost, refund]
  • 0 ≤ cost, refund ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsGrowing Capital Project by Project HardDistinct Word Shorthands HardMost Orders by Their Deadlines HardNarrowest Range Touching Every List HardTwo Marks in Every Range Hard
loading Python…
Input
operations=[[6, 2], [3, 5], [4, 0]]
Expected
11

Run checks the first 3 tests in your browser. Submit checks all 112 tests on the server, hidden ones included.