Fruit Into Baskets

Practice this coding question on Coding Gurukul.

Problem statement

A fruit collector walks along a row of trees carrying two baskets. Each basket can hold any number of fruits but only one fruit type. After choosing a starting tree, the collector takes one fruit from every following tree until a third type would be required. Your task Find the largest number of fruits obtainable, equivalently the length of the longest contiguous subarray containing at most two distinct values. Important details You may choose any starting position but cannot skip a tree once collection begins. One fruit type is also valid. Repeated type numbers refer to the same type regardless of their distance along the row. Worked example For types [1, 2, 1, 3, 3], starting at the third tree gives [1, 3, 3], while starting at the first gives [1, 2, 1]. Both collect three fruits, the maximum.

Input format

The first line contains n. The next line contains n space-separated integers; for n = 0 this line may be empty.

Output format

Print the maximum count.

Constraints

1 <= n <= 100000; 0 <= types < n.

Sample input

5
1 2 1 3 3

Sample output

3

Sign in to run or submit a solution in C++, Java or Python.