Fruit Into Baskets
You are given an integer array fruits, where fruits[i] is the type of fruit on the ith tree. Starting at any tree, collect exactly one fruit from each…
You are given an integer array `fruits`, where `fruits[i]` is the type of fruit on the `i`th tree. Starting at any tree, collect exactly one fruit from each consecutive tree while moving right. You have two baskets, and each basket may hold only one fruit type. Return the maximum number of fruits you can collect.
- `1 <= fruits.length <= 10^5` - `0 <= fruits[i] <= 10^9` - The interactive visualizer accepts at most 12 values; longer valid inputs are execution-only.
Example 1: input fruits = [1,2,1]; output 3. Window by window: [1] holds 1 fruit; [1,2] holds 2 fruits with types 1 and 2; [1,2,1] holds 3 fruits and still only types 1 and 2, so both baskets are enough. The whole row is collected, so the answer is 3.
Example 2: input fruits = [1,2,3,2,2]; output 4. Window by window: [1] holds 1 fruit; [1,2] holds 2; adding 3 would make three types, so the start moves past the 1 and the window becomes [2,3] with 2 fruits; [2,3,2] holds 3; [2,3,2,2] holds 4. The best window is [2,3,2,2], which has two fruit types and length 4.
Category: Sliding Window. Topic: sliding-window. Difficulty: Medium. Patterns: sliding-window, hashing, two-pointers.