#C2435. Longest Balanced Subarray

    ID: 45751 Type: Default 1000ms 256MiB

Longest Balanced Subarray

Longest Balanced Subarray

Given an array A of integers which can only be -1, 0, or 1, find the length of the longest contiguous subarray that is balanced, meaning it contains an equal number of -1s, 0s, and 1s.

The subarray can start and end at any indices of A (0-indexed). If no such balanced subarray exists, return 0.

Note: The balanced subarray must have counts of -1, 0 and 1 equal to each other. For example, the subarray [1, -1, 0] is balanced, but [1, 1, -1, 0] is not.

Example:

Input: 7
       1 -1 1 0 0 -1 1
Output: 6

In the above example, the longest balanced subarray is of length 6.

inputFormat

Standard Input:

  • The first line contains a single integer n, the size of the array A.
  • The second line contains n space-separated integers, each of which is -1, 0, or 1.

outputFormat

Standard Output:

  • Output a single integer, the length of the longest balanced subarray.
## sample
7
1 -1 1 0 0 -1 1
6