|
| 1 | +/** |
| 2 | + * 904. Fruit Into Baskets |
| 3 | + * https://leetcode.com/problems/fruit-into-baskets/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are visiting a farm that has a single row of fruit trees arranged from left to right. |
| 7 | + * The trees are represented by an integer array fruits where fruits[i] is the type of fruit |
| 8 | + * the ith tree produces. |
| 9 | + * |
| 10 | + * You want to collect as much fruit as possible. However, the owner has some strict rules |
| 11 | + * that you must follow: |
| 12 | + * - You only have two baskets, and each basket can only hold a single type of fruit. There |
| 13 | + * is no limit on the amount of fruit each basket can hold. |
| 14 | + * - Starting from any tree of your choice, you must pick exactly one fruit from every tree |
| 15 | + * (including the start tree) while moving to the right. The picked fruits must fit in one |
| 16 | + * of your baskets. |
| 17 | + * - Once you reach a tree with fruit that cannot fit in your baskets, you must stop. |
| 18 | + * |
| 19 | + * Given the integer array fruits, return the maximum number of fruits you can pick. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} fruits |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var totalFruit = function(fruits) { |
| 27 | + const map = new Map(); |
| 28 | + let result = 0; |
| 29 | + let start = 0; |
| 30 | + |
| 31 | + for (let end = 0; end < fruits.length; end++) { |
| 32 | + map.set(fruits[end], (map.get(fruits[end]) || 0) + 1); |
| 33 | + |
| 34 | + while (map.size > 2) { |
| 35 | + map.set(fruits[start], map.get(fruits[start]) - 1); |
| 36 | + if (map.get(fruits[start]) === 0) { |
| 37 | + map.delete(fruits[start]); |
| 38 | + } |
| 39 | + start++; |
| 40 | + } |
| 41 | + |
| 42 | + result = Math.max(result, end - start + 1); |
| 43 | + } |
| 44 | + |
| 45 | + return result; |
| 46 | +}; |
0 commit comments