All problems

Contiguous Array

Medium · prefix sum

You are given a list nums that contains only 0s and 1s.

A balanced part is a non-empty run of neighbouring elements of nums that contains the same number of 0s as 1s. Return the length of the longest balanced part.

If the list has no balanced part, return 0.

Examples

Example 1

Input: nums = [0, 1]

Output: 2

The whole list has one 0 and one 1.

Example 2

Input: nums = [1, 1, 0, 1, 0, 0, 1]

Output: 6

The first six elements, 1 1 0 1 0 0, hold three 1s and three 0s. All seven elements would hold four 1s and three 0s.

Example 3

Input: nums = [1, 1, 1]

Output: 0

There is no 0 at all, so no part can be balanced.

Constraints