← DiffPush

Largest subarray with 0sum

DiffPush Tier Arrays · Hard O(n) · O(n)

Longest Balanced Window in a Credit Ledger

A settlement ledger records signed credits per interval, and a balanced window is a contiguous run whose credits cancel out to zero. The auditors want the widest such window to sample, since it hides the largest stretch of offsetting activity. Credits may be positive or negative, so cumulative totals can wander.

Input: An integer n and an array A of n signed integers.

Output: The length of the longest contiguous subarray whose elements sum to zero, or 0 when no such subarray exists.

Constraints

Examples

Example 1

Input: {"n":8,"A":[15,-2,2,-8,1,7,10,23]}
Output: 5
The window -2,2,-8,1,7 cancels completely and spans five intervals, the widest such run.

Example 2

Input: {"n":3,"A":[1,-1,3]}
Output: 2
The opening pair cancels to zero and gives a balanced window of length 2.

Solve this in your browser →

Also on LeetCode ↗