Skip to content

Commit c161f3d

Browse files
committed
Add solution #904
1 parent 8840990 commit c161f3d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,7 @@
714714
901|[Online Stock Span](./0901-online-stock-span.js)|Medium|
715715
902|[Numbers At Most N Given Digit Set](./0902-numbers-at-most-n-given-digit-set.js)|Hard|
716716
903|[Valid Permutations for DI Sequence](./0903-valid-permutations-for-di-sequence.js)|Hard|
717+
904|[Fruit Into Baskets](./0904-fruit-into-baskets.js)|Medium|
717718
905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy|
718719
909|[Snakes and Ladders](./0909-snakes-and-ladders.js)|Medium|
719720
912|[Sort an Array](./0912-sort-an-array.js)|Medium|

Diff for: solutions/0904-fruit-into-baskets.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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

Comments
 (0)