没看答案,滑动窗口问题。
import sys
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
length = len(fruits)
window = {}
left, right = 0, 0
res = -sys.maxsize
while right < length:
num = fruits[right]
right += 1
if len(window) < 2:
if num not in window.keys():
window[num] = 1
else:
window[num] += 1
else:
if num not in window.keys():
window[num] = 1
while len(window) > 2:
tmp = fruits[left]
left += 1
window[tmp] -= 1
if window[tmp] == 0:
del window[tmp]
else:
window[num] += 1
res = res if res >= sum(window.values()) else sum(window.values())
return res