Skip to content

Commit a60b80a

Browse files
authored
Merge pull request neetcode-gh#2221 from AkifhanIlgaz/0904
Create: 0904-fruit-into-baskets
2 parents e7fdf97 + 551c460 commit a60b80a

File tree

4 files changed

+112
-0
lines changed

4 files changed

+112
-0
lines changed

go/0904-fruit-into-baskets.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package main
2+
3+
func main() {
4+
5+
}
6+
7+
func totalFruit(fruits []int) int {
8+
count := map[int]int{}
9+
left, total, res := 0, 0, 0
10+
11+
for _, fruit := range fruits {
12+
count[fruit]++
13+
total++
14+
15+
for len(count) > 2 {
16+
f := fruits[left]
17+
count[f]--
18+
total--
19+
left++
20+
if count[f] == 0 {
21+
delete(count, f)
22+
}
23+
}
24+
res = max(res, total)
25+
}
26+
return res
27+
}
28+
29+
func max(a, b int) int {
30+
if a > b {
31+
return a
32+
}
33+
return b
34+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[]} fruits
3+
* @return {number}
4+
*/
5+
var totalFruit = function (fruits) {
6+
let count = new Map();
7+
let [left, total, res] = [0, 0, 0];
8+
9+
for (fruit of fruits) {
10+
count.set(fruit, (count.get(fruit) || 0) + 1);
11+
total++;
12+
13+
while (count.size > 2) {
14+
let f = fruits[left];
15+
count.set(f, count.get(f) - 1);
16+
total -= 1;
17+
left += 1;
18+
if (!count.get(f)) {
19+
count.delete(f);
20+
}
21+
}
22+
res = Math.max(res, total);
23+
}
24+
25+
return res;
26+
};

rust/0904-fruit-into-baskets.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
use std::collections::HashMap;
2+
3+
impl Solution {
4+
pub fn total_fruit(fruits: Vec<i32>) -> i32 {
5+
let mut count = HashMap::new();
6+
let (mut left, mut total, mut res) = (0, 0, 0);
7+
8+
for fruit in &fruits {
9+
*count.entry(*fruit).or_insert(0) += 1;
10+
total += 1;
11+
12+
while count.len() > 2 {
13+
let f = fruits[left];
14+
match count.remove(&f) {
15+
Some(v) if v > 1 => {
16+
count.insert(f, v - 1);
17+
}
18+
_ => {}
19+
}
20+
total -= 1;
21+
left += 1;
22+
}
23+
24+
res = res.max(total);
25+
}
26+
27+
res
28+
}
29+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function totalFruit(fruits: number[]): number {
2+
let count = new Map();
3+
let [left, total, res] = [0, 0, 0];
4+
5+
for (let fruit of fruits) {
6+
count.set(fruit, (count.get(fruit) || 0) + 1);
7+
total++;
8+
9+
while (count.size > 2) {
10+
let f = fruits[left];
11+
count.set(f, count.get(f) - 1);
12+
total--;
13+
left++;
14+
if (!count.get(f)) {
15+
count.delete(f);
16+
}
17+
}
18+
19+
res = Math.max(res, total);
20+
}
21+
22+
return res;
23+
}

0 commit comments

Comments
 (0)