Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3310dca

Browse files
Initial commit
1 parent 4a47338 commit 3310dca

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

‎fruits_into_baskets_grok.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Fruits into Baskets (medium)
2+
# Given an array of characters where each character represents a fruit tree, you are given two baskets, and your goal is to put maximum number of fruits in each basket. The only restriction is that each basket can have only one type of fruit.
3+
# You can start with any tree, but you can’t skip a tree once you have started. You will pick one fruit from each tree until you cannot, i.e., you will stop when you have to pick from a third fruit type.
4+
# Write a function to return the maximum number of fruits in both baskets.
5+
6+
# Input: Fruit=['A', 'B', 'C', 'A', 'C']
7+
# Output: 3
8+
# Explanation: We can put 2 'C' in one basket and one 'A' in the other from the subarray ['C', 'A', 'C']
9+
10+
def fruits_into_baskets(fruits):
11+
window_start = 0
12+
max_length = 0
13+
fruit_frequency = {}
14+
15+
# try to extend the range [window_start, window_end]
16+
for window_end in range(len(fruits)):
17+
right_fruit = fruits[window_end]
18+
if right_fruit not in fruit_frequency:
19+
fruit_frequency[right_fruit] = 0
20+
fruit_frequency[right_fruit] += 1
21+
22+
# shrink the sliding window, until we are left with '2' fruits in the fruit frequency dictionary
23+
while len(fruit_frequency) > 2:
24+
left_fruit = fruits[window_start]
25+
fruit_frequency[left_fruit] -= 1
26+
if fruit_frequency[left_fruit] == 0:
27+
del fruit_frequency[left_fruit]
28+
window_start += 1 # shrink the window
29+
max_length = max(max_length, window_end-window_start + 1)
30+
return max_length
31+
32+
def fruits_into_baskets2(fruits):
33+
fruit_map = {}
34+
window_start = 0
35+
max_fruits = 0
36+
37+
for window_end in range(len(fruits)):
38+
end_fruit = fruits[window_end]
39+
40+
fruit_map[end_fruit] = fruit_map.get(end_fruit, 0) + 1
41+
42+
while len(fruit_map) > 2:
43+
start_fruit = fruits[window_start]
44+
45+
fruit_map[start_fruit] -= 1
46+
if fruit_map[start_fruit] == 0:
47+
del fruit_map[start_fruit]
48+
49+
window_start += 1
50+
51+
max_fruits = max(max_fruits, window_end - window_start + 1)
52+
53+
return max_fruits
54+
55+
def main():
56+
print("Maximum number of fruits: " + str(fruits_into_baskets(['A', 'B', 'C', 'A', 'C'])))
57+
print("Maximum number of fruits: " + str(fruits_into_baskets(['A', 'B', 'C', 'B', 'B', 'C'])))
58+
59+
60+
main()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /