Created
August 4, 2025 19:00
-
-
Save tatsuyax25/fa55139461d1b03cb07f4a0a4dcdd1c2 to your computer and use it in GitHub Desktop.
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces. You want to collect as much fruit as possible.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} fruits | |
* @return {number} | |
*/ | |
var totalFruit = function(fruits) { | |
let maxFruits = 0; | |
let left = 0; | |
const basket = new Map(); // Holds fruit type and count | |
// Move the right boundary of the window | |
for (let right = 0; right < fruits.length; right++) { | |
const fruit = fruits[right]; | |
// Add current fruit to the basket (or update count) | |
basket.set(fruit, (basket.get(fruit) || 0) + 1); | |
// If we have more than two fruit types, shrink from the left | |
while (basket.size > 2) { | |
const leftFruit = fruits[left]; | |
basket.set(leftFruit, basket.get(leftFruit) - 1); | |
if (basket.get(leftFruit,) === 0) { | |
basket.delete(leftFruit); // Remove when count hits zero | |
} | |
left++; // Move window's left side | |
} | |
// Update max fruits picked in a valid window | |
maxFruits = Math.max(maxFruits, right - left + 1); | |
} | |
return maxFruits; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment