#C14988. Longest Contiguous Sublist with Two Distinct Integers

    ID: 44697 Type: Default 1000ms 256MiB

Longest Contiguous Sublist with Two Distinct Integers

Longest Contiguous Sublist with Two Distinct Integers

Given an array of integers, your task is to find the length of the longest contiguous subarray that contains exactly two distinct integers. Formally, for an array \(a = [a_1, a_2, \dots, a_n]\), determine the maximum length \(L\) such that there exists an interval \([i, j]\) with exactly two distinct integers in \(a[i \dots j]\). If the array contains fewer than two distinct integers, then the answer is simply the length of the entire array.

Example:

  • For [1, 2, 1, 2, 3], the longest contiguous subarray with exactly two distinct integers is [1, 2, 1, 2] with length 4.
  • For [1, 2, 3, 4], any contiguous subarray containing two distinct integers is of length 2.
  • For [1, 1, 1, 1], the entire array is valid with length 4.

Note: It is recommended to use an optimal algorithm (for example, using a sliding window technique) to solve this problem in \(O(n)\) time.

inputFormat

The input is given via standard input (stdin) as follows:

  1. The first line contains a non-negative integer \(n\) representing the number of elements in the array.
  2. If \(n > 0\), the second line contains \(n\) space-separated integers representing the elements of the array. If \(n = 0\), there is no second line.

outputFormat

Output a single integer to standard output (stdout) — the length of the longest contiguous subarray that contains exactly two distinct integers.

## sample
5
1 2 1 2 3
4

</p>