Loading...
Loading...
On a school trip to a farm in Ratnagiri, Meera walks along a row of n trees. Each tree has one kind of fruit, written as a number code. She has two baskets, and each basket can hold only one kind of fruit, but as much of it as she likes.
She picks one fruit from every tree in a run of consecutive trees. Print the largest number of trees she can pick from, so that all fruits fit in her two baskets.
Example 1
Input
7 1 2 1 3 3 2 2
Output
4
Trees 4 to 7 (3 3 2 2) have only two kinds. Trees 1 to 3 give only 3.
Example 2
Input
3 5 5 5
Output
3
One kind of fruit fits easily.
Try the problem first. Open one hint at a time.
Keep a run of trees from left to right and, for each fruit code in it, how many trees have it.
Codes go up to 10^9, so use a HashMap<Integer, Integer> for the counts, not an array.
When a third kind joins, move left forward and lower counts until one kind reaches 0. Remove that kind from the map.
The number of kinds in the run is map.size().
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor