1
1
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
12
7
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
14
13
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
20
17
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