Skip to content

Commit 7030052

Browse files
committed
Runtime 915 ms (Top 76.5%) | Memory 20.0 MB (Top 83.27%)
1 parent fb2a50c commit 7030052

File tree

1 file changed

+25
-36
lines changed

1 file changed

+25
-36
lines changed
Lines changed: 25 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,29 @@
11
class Solution:
2-
def totalFruit(self, nums: List[int]) -> int:
3-
"""
4-
This problem asks us to find the maximum length of a subarray,
5-
which has maximum 2 unique numbers.
6-
I changed the input "fruit -> nums" for easy typing.
7-
"""
8-
#Define the budget k we can spend
9-
k = 2
10-
left = 0
11-
hashmap = {}
2+
def totalFruit(self, fruits: List[int]) -> int:
3+
ans=0
4+
fruitdict=defaultdict()
5+
stack=[]
6+
i,j=0,0
127

13-
for right in range(len(nums)):
8+
while j<len(fruits):
9+
if fruits[j] not in fruitdict and len(fruitdict)<2:
10+
stack.append(fruits[j])
11+
fruitdict[fruits[j]]=j
12+
j+=1
1413

15-
# when we meet a new unique number,
16-
# add it to the hashmap and lower the budget
17-
if nums[right] not in hashmap:
18-
k -= 1
19-
hashmap[nums[right]] = 1
14+
elif fruits[j] in fruitdict:
15+
fruitdict[fruits[j]]=j
16+
j+=1
2017

21-
# when we meet a number in our window
22-
elif nums[right] in hashmap:
23-
hashmap[nums[right]] += 1
24-
25-
# when we exceed our budget
26-
if k < 0:
27-
# when we meet a number that can help us to save the budget
28-
if hashmap[nums[left]] == 1:
29-
del hashmap[nums[left]]
30-
k += 1
31-
# otherwise we just reduce the freq
32-
else:
33-
hashmap[nums[left]] -= 1
34-
left += 1
35-
36-
"""
37-
We never shrink our window, we just expand the window when it satisfies the condition
38-
So, finally the window size is the maximum
39-
"""
40-
return right - left + 1
18+
else:
19+
if fruitdict[stack[0]]>fruitdict[stack[1]] :
20+
i = fruitdict[stack[1]]+1
21+
del fruitdict[stack[1]]
22+
stack.pop()
23+
else:
24+
i = fruitdict[stack[0]]+1
25+
del fruitdict[stack[0]]
26+
stack.pop(0)
27+
28+
ans=max(ans,j-i)
29+
return ans

0 commit comments

Comments
 (0)