Skip to content

Commit 84d75d8

Browse files
committed
[medium] 904. Fruit Into Baskets
1 parent 227232d commit 84d75d8

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

904.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import unittest
2+
from typing import List
3+
4+
5+
class Solution:
6+
def totalFruit(self, fruits: List[int]) -> int:
7+
table = {}
8+
9+
left = 0
10+
right = 0
11+
res = 0
12+
size = len(fruits)
13+
14+
while right < size:
15+
current_fruit = fruits[right]
16+
oldest_fruid = fruits[left]
17+
18+
table[current_fruit] = table.get(current_fruit, 0) + 1
19+
20+
if len(table.keys()) > 2:
21+
table[oldest_fruid] -= 1
22+
23+
if table[oldest_fruid] == 0:
24+
del table[oldest_fruid]
25+
26+
left += 1
27+
28+
right += 1
29+
30+
res = max(res, right - left)
31+
32+
return res
33+
34+
35+
class Tests(unittest.TestCase):
36+
def test_one(self):
37+
self.assertEqual(Solution().totalFruit(fruits=[1, 2, 1]), 3)
38+
39+
def test_two(self):
40+
self.assertEqual(
41+
Solution().totalFruit(fruits=[5, 9, 0, 9, 6, 9, 6, 9, 9, 9]), 7
42+
)
43+
44+
45+
if __name__ == "__main__":
46+
unittest.main()

0 commit comments

Comments
 (0)