Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Sliding window

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Sliding window

Fruit Into Baskets

intermediatelayer B5 · Sliding window5 tests

You walk along a row of trees given as fruits, where fruits[i] is the type of fruit on tree i. You carry two baskets and each basket can hold only one type of fruit (any amount of it). You pick exactly one fruit from every tree you pass, and you must stop when you reach a tree whose fruit fits in neither basket.

Return the maximum number of fruits you can collect — that is, the length of the longest contiguous subarray containing at most 2 distinct values.

  • You may start at any tree
  • An empty row yields 0
  • Target complexity: O(n)

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen