#C1299. Maximize Balanced Subarray Length with One Modification

    ID: 42477 Type: Default 1000ms 256MiB

Maximize Balanced Subarray Length with One Modification

Maximize Balanced Subarray Length with One Modification

You are given an array of integers of length \(N\). You are allowed to perform at most one modification on the array: choose any element and replace it with any integer of your choice.

Your goal is to maximize the length of a contiguous subarray in which the number of positive elements equals the number of negative elements. Note that zero is considered neutral and does not contribute to either count.

Definition: A subarray is a contiguous portion of the array.

Balanced subarray condition: Let \(pos\) be the count of positive numbers and \(neg\) be the count of negative numbers in the subarray, then we require \(pos = neg\).

Constraints:

  • \(1 \leq N \leq 10^5\)
  • \(-10^9 \leq A[i] \leq 10^9\)

If no balanced subarray exists, the answer is 0. You may opt not to perform any modification if the array already contains an optimal subarray.

Example 1:

Input:
5
1 -1 1 1 -1

Output: 4

</p>

Example 2:

Input:
4
1 1 -1 -1

Output: 4

</p>

Example 3:

Input:
3
1 2 3

Output: 2

</p>

inputFormat

The input is read from stdin and has the following format:

  1. The first line contains a single integer \(N\), denoting the number of elements in the array.
  2. The second line contains \(N\) space-separated integers representing the array \(A\).

outputFormat

Output to stdout a single integer: the maximum length of a contiguous subarray which can be made balanced (equal number of positive and negative numbers) by performing at most one modification.

## sample
5
1 -1 1 1 -1
4

</p>