#C2595. Longest Subarray with At Most Two Distinct Integers

    ID: 45928 Type: Default 1000ms 256MiB

Longest Subarray with At Most Two Distinct Integers

Longest Subarray with At Most Two Distinct Integers

You are given an array of integers. Your task is to determine the length of the longest contiguous subarray that contains at most two distinct integers. Formally, given an array \(a_1, a_2, \ldots, a_n\), find the maximum length \(L\) such that there exists an index \(i\) where the subarray \(a_i, a_{i+1}, \ldots, a_{i+L-1}\) contains at most two distinct values.

Example:

  • For the input array [1, 2, 1], the whole array contains only two distinct integers so the answer is 3.
  • For the input array [0, 1, 2, 2], the longest valid subarray is [1, 2, 2] with length 3.
  • For the input array [1, 2, 3, 4, 5], any subarray with two distinct integers has length 2.

The intended solution uses the sliding window technique with a hash map to keep track of the last occurrence of each integer in the current window. The time complexity of an optimal solution is \(O(n)\).

inputFormat

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

  1. The first line contains an integer \(n\) denoting the number of elements in the array.
  2. The second line contains \(n\) space-separated integers.

outputFormat

Output a single integer representing the length of the longest contiguous subarray that contains at most two distinct integers.

## sample
3
1 2 1
3