Skip to content

Commit 006c325

Browse files
author
Partho Biswas
committed
leetcode. 904. Fruit Into Baskets
1 parent 0313be0 commit 006c325

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution(object):
2+
3+
# outer for loop runs for all characters and the inner while loop processes each character only once,
4+
# therefore the time complexity of the algorithm will be O(N+N) which is asymptotically equivalent to O(N)
5+
# algorithm runs in constant space O(1)
6+
def totalFruit(self, tree):
7+
"""
8+
:type tree: List[int]
9+
:rtype: int
10+
"""
11+
return self.totalNumbberOfKFruit(tree, 2)
12+
13+
# maxFruitType is similar to number of baskets where each baskets can contain only one type of fruit
14+
def totalNumbberOfKFruit(self, tree, maxFruitType):
15+
windowStart = 0
16+
maxLength = 0
17+
fruitFrequency = {}
18+
19+
# try to extend the range [windowStart, windowEnd]
20+
for windowEnd in range(len(tree)):
21+
rightFruitType = tree[windowEnd]
22+
if rightFruitType not in fruitFrequency:
23+
fruitFrequency[rightFruitType] = 0
24+
fruitFrequency[rightFruitType] += 1
25+
26+
# shrink the sliding window from the left side, until we are left with last 2 fruits
27+
while len(fruitFrequency) > maxFruitType:
28+
leftFruitType = tree[windowStart]
29+
fruitFrequency[leftFruitType] -= 1
30+
if fruitFrequency[leftFruitType] == 0:
31+
del fruitFrequency[leftFruitType]
32+
windowStart += 1 # shrink the window
33+
maxLength = max(maxLength, windowEnd - windowStart + 1)
34+
return maxLength
35+
36+
37+
38+
39+
sol = Solution()
40+
input = [1,1,2,3,2,2,2]
41+
output = sol.totalFruit(input)
42+
print('Total Fruit: ', output)

0 commit comments

Comments
 (0)