#C5904. Maximum Balanced Subarray

    ID: 49605 Type: Default 1000ms 256MiB

Maximum Balanced Subarray

Maximum Balanced Subarray

You are given a binary sequence of length (n) consisting of '0's and '1's. A contiguous subarray is said to be balanced if it contains an equal number of '0's and '1's. Your task is to find the maximum length of any balanced contiguous subarray.

Consider the transformation where each '1' is treated as +1 and each '0' as -1. If we compute the prefix sum of this transformed sequence, then a balanced subarray exists between two indices where the prefix sums are equal. Mathematically, if (P(i)) is the prefix sum up to index (i), then for indices (i < j), if (P(i) = P(j)) the subarray from (i+1) to (j) is balanced, and its length is (j - i). You need to output the maximum such length.

Formally, find (\max{j-i \mid P(i) = P(j), ; 0 \le i < j \le n}).

inputFormat

Input is read from standard input (stdin). The first line contains an integer (n), representing the length of the binary sequence. The second line contains a binary string of length (n) consisting only of the characters '0' and '1'.

outputFormat

Output the maximum length of a contiguous balanced subarray to standard output (stdout).## sample

8
11011010
6