Problem 207543 · medium · Level 02 Linear Data Structures

Minimum Opening Balance

arrays · prefix-sums · running-statistics

A shop's cash register starts the day with some amount and then processes changes in order (positive for sales, negative for refunds). The register must never hold less than 1. Return the smallest positive opening amount that guarantees this.

Examples

Input:  changes = [-3, 2, -3, 4, 2]
Output: 5
Explanation: Starting at 5, the register holds 2, 4, 1, 5, 7 and never drops below 1.

Input:  changes = [1, 2]
Output: 1
Explanation: The amount only grows, so the minimum positive start is 1.

Input:  changes = [1, -2, -3]
Output: 5

Constraints

  • 0 <= len(changes) <= 10**5
  • -10**4 <= changes[i] <= 10**4
  • Target: O(n) time, O(1) extra space.

Goals

  • Track the minimum of a running sum
  • Turn the lowest dip into the required starting value
Starting Python…