#C7256. Longest Balanced Subarray

    ID: 51107 Type: Default 1000ms 256MiB

Longest Balanced Subarray

Longest Balanced Subarray

You are given an array of integers where each element is either 1 or -1. Your task is to find the length of the longest contiguous subarray that contains an equal number of 1 and -1.

The idea is to reframe the problem by considering 1 as +1 and -1 as -1. A subarray with equal number of 1s and -1s will have a sum of 0.

Formally, if the given array is nums of length n, you are required to determine the maximum length L such that there exists indices i and j with 0 ≤ i < j < n for which the subarray nums[i..j] has a total sum of 0. In mathematical terms, you need to find:

[ L = \max { j - i , : ; \sum_{k=i}^{j} nums[k] = 0 } ]

If no such subarray exists, output 0.

inputFormat

The input is read from standard input (stdin) and consists of two lines:

  1. The first line contains a single integer n (the number of elements in the array).
  2. The second line contains n space-separated integers, each being either 1 or -1.

outputFormat

Output a single integer to standard output (stdout) representing the length of the longest contiguous subarray with an equal number of 1 and -1.

## sample
8
1 -1 1 1 -1 -1 1 -1
8