Problem 324326 · medium · Phase 03 Linear Management & Searching

Two-Crate Harvest

sliding window · variable-size window · hash map

An orchard row is a list trees where trees[i] is the kind of fruit on tree i. You walk along the row picking one fruit from every tree you pass, starting anywhere and stopping when you must. You carry exactly two crates, each holding a single kind of fruit, so you cannot pass a tree of a third kind. Return the maximum number of fruits you can collect.

Examples

Input:  trees = [1, 2, 1]
Output: 3

Input:  trees = [0, 1, 2, 2]
Output: 3
Explanation: pick [1, 2, 2]; starting at 0 would need three crates.

Input:  trees = [1, 2, 3, 2, 2]
Output: 4

Constraints

  • 1 <= len(trees) <= 10**5
  • 0 <= trees[i] <= 10**9
  • Target complexity: O(n) time; trying every starting tree is too slow for the largest tests.

Goals

  • Recognise a 'longest window with at most two kinds' constraint
  • Keep the window valid with a small frequency map
Starting Python…