PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#PS0000141. Đoạn nhị phân cân bằng dài nhất (Contiguous Array)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đoạn nhị phân cân bằng dài nhất (Contiguous Array)

Contiguous Array

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Given a binary array a1,…,ana_1,\ldots,a_n, call a contiguous interval balanced when it contains equally many zeros and ones. Find the maximum length of a nonempty balanced interval, or 0 if none exists.

Input

  • Line 1: integer nn, the array length.
  • Line 2: nn integers a1,…,ana_1,\ldots,a_n in order.

Output

Print the maximum balanced interval length, or 0 if none exists.

Subtasks

  • Subtask 1 (20 points): 1≤n≤10001\le n\le 1000; 1≤i≤n1\le i\le n; ai∈{0,1}a_i\in\{0,1\}.
  • Subtask 2 (30 points): 1≤n≤1000001\le n\le 100000; 1≤i≤n1\le i\le n; ai∈{0,1}a_i\in\{0,1\}; ai≠ai+1a_i\ne a_{i+1} for all 1≤i<n1\le i<n.
  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; 1≤i≤n1\le i\le n; ai∈{0,1}a_i\in\{0,1\}.

Example 1

Input

2
0 1

Output

2

Explanation

The whole array has one zero and one one, so the maximum length is 2.

Example 2

Input

3
0 1 0

Output

2

Explanation

Intervals [1,2][1,2] and [2,3][2,3] are balanced. The whole array has two zeros and one one, so length 3 is impossible.

Example 3

Input

9
0 1 1 1 1 1 0 0 0

Output

6

Explanation

Interval [4,9][4,9] has three ones and three zeros. A balanced length is even; both length-8 intervals contain only three zeros, so 6 is maximal.