Problem statement

https://leetcode.com/problems/fruit-into-baskets/

Solution

The idea is to use sliding window: we need to find the longest one where we have at most 2 elements.

Complexity

Time complexity is O(n), space complexity is O(1).

Code

class Solution:
    def totalFruit(self, tree):
        beg, end, n, cnt = 0, 0, len(tree), Counter()
        ans = 0
        while end < n:
            if tree[end] in cnt or len(cnt) < 2:
                cnt[tree[end]] += 1
                end += 1
                ans = max(ans, end - beg)
            else:
                cnt[tree[beg]] -= 1
                if cnt[tree[beg]] == 0: cnt.pop(tree[beg])
                beg += 1
                
        return ans