In a row of trees, the i-th tree produces fruit with type tree[i].
You start at any tree of your choice, then repeatedly perform the following steps:

Add one piece of fruit from this tree to your baskets.  If you cannot, stop.
Move to the next tree to the right of the current tree.  If there is no tree to the right, stop.

Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.
You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.
What is the total amount of fruit you can collect with this procedure?
 
Example 1:
Input: [1,2,1]
Output: 3
Explanation: We can collect [1,2,1].


Example 2:
Input: [0,1,2,2]
Output: 3
Explanation: We can collect [1,2,2].
If we started at the first tree, we would only collect [0, 1].


Example 3:
Input: [1,2,3,2,2]
Output: 4
Explanation: We can collect [2,3,2,2].
If we started at the first tree, we would only collect [1, 2].


Example 4:
Input: [3,3,3,1,2,1,1,2,3,3,4]
Output: 5
Explanation: We can collect [1,2,1,1,2].
If we started at the first tree or the eighth tree, we would only collect 4 fruits.

 



Note:

1 <= tree.length <= 40000
0 <= tree[i] < tree.length

```python

USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
    import resource as _res
except Exception:
    _res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
    from typing import *
except Exception:
    pass
try:
    sys.setrecursionlimit(1_000_000)
except Exception:
    pass
try:
    import site as _site
    try:
        _sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
        for _p in _sys_sites:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
    try:
        _usp = _site.getusersitepackages()
        if isinstance(_usp, str):
            _usp = [_usp]
        for _p in _usp:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
except Exception:
    pass

def _disabled_input(*args, **kwargs):
    raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input

ns = {"__name__": "__judge__"}  # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
    if not _k.startswith("_"):
        ns[_k] = _v
_CODE = 'class Solution:\n    # def totalFruit(self, tree):\n    #     # scan the array\n    #     fruit_block = []\n    #     #fruit_block entity = [left_most index in fruit, weight]\n    #     for i in range(len(tree)):\n    #         if i == 0 or tree[i] != tree[i-1]:\n    #             fruit_block.append([i, 1 ])\n    #         elif tree[i] == tree[i-1]:\n    #             fruit_block[-1][1] += 1\n    #     # print(fruit_block)\n    #     max_fruit = 0\n    #     i = 0\n    #     while i < len(fruit_block):\n    #         old_i = i\n    #         type_fruit = []\n    #         weight = 0\n    #         for j in range(i, len(fruit_block)):\n    #             if tree[fruit_block[j][0]] not in type_fruit:\n    #                 type_fruit.append(tree[fruit_block[j][0]])\n    #             weight += fruit_block[j][1]\n    #             # print(\\"type fruit \\", type_fruit)\n    #             # print(\\"weight \\", weight)\n    #             if len(type_fruit) > 2:\n    #                 # print(\\"break\\")\n    #                 i = j -1\n    #                 break\n    #             max_fruit = max(max_fruit, weight)\n    #             if j == len(fruit_block):\n    #                 break\n    #         if i == old_i:\n    #             break\n    #     return max_fruit\n            \n        \n#     def totalFruit(self, tree: List[int]) -> int:\n        \n#         greattest_count = 0\n#         for i in range(len(tree)):\n#             if i > 0 and tree[i] == tree[i-1]:\n#                 print(i)\n#                 continue\n#             if i > 2 and tree[i] == tree[i-2] and tree[i-1] == tree[i-3] and tree[i] != tree[i-1] and self.checkRepeat(tree, i):\n#                 #add function to define tree[i-1] == the newest tree after ones that look like tree[i]\n#                 print(i)\n#                 continue\n#             fruit = self.pickFruit(i, tree)\n#             if fruit > greattest_count:\n#                 greattest_count = fruit\n#         return greattest_count\n                \n#             # print(count)\n#             # print(greattest_count)\n        \n#         return greattest_count\n    \n#     def checkRepeat(self,tree, i):\n#         for j in range(i, len(tree)):\n#             if tree[j] != tree[i]:\n#                 return tree[j]==tree[i-1]\n#         return True\n                \n    \n#     def pickFruit(self, i, tree):\n#         count = 0\n#         basket=[\\"\\", \\"\\"]\n#         for j in range(i, len(tree)):\n#             if basket[0] == \\"\\":\n#                 basket[0] = tree[j]\n#                 # print(\\"basket1: \\", basket[0])\n#                 count += 1\n#                 # print(\\"basket1\\")\n#             elif tree[j] == basket[0]:\n#                 count+=1\n#                 # print(\\"already in basket1\\")\n#             elif basket[1] == \\"\\":\n#                 basket[1] = tree[j]\n#                 count += 1\n#                 # print(\\"basket2: \\", basket[1])\n#             elif tree[j] == basket[1]:\n#                 count += 1\n#                 # print(\\"already in basket2\\")\n#             elif tree[j] not in basket:\n#                 return count\n#             if j == len(tree)-1:\n#                 return count\n\n    def totalFruit(self, tree: List[int]) -> int:\n        basket1 = -1\n        basket2 = -1\n        max_fruit = 0\n        start = 0\n        end = 0\n        i = 0\n        while i < len(tree):\n            if tree[i] == basket1 or tree[i] == basket2:\n                if tree[i] != tree[i-1]:\n                    end = i\n                i += 1\n                continue\n            if basket1 == -1:\n                basket1 = tree[i]\n                end = i\n                i += 1\n                continue\n            if basket2 == -1:\n                basket2 = tree[i]\n                end = i\n                i += 1\n                continue\n            print(i)\n            print(end)\n            weight = i - start \n            max_fruit = max(max_fruit, weight)\n            #max_fruit = 2 - 0 = 2\n            i = end # 1\n            start = end # 1\n            basket1 = -1\n            basket2 = -1\n        # if start == 0:\n        #     weight = len(tree)\n        # else:\n        #     weight = len(tree) - start - 1\n        weight = len(tree) - start\n            \n        \n        max_fruit = max(max_fruit, weight)\n            \n        return max_fruit'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)

_target = None
_fn_name = 'totalFruit'
if _fn_name:
    if "Solution" in ns:
        try:
            _obj = ns["Solution"]()
            if hasattr(_obj, _fn_name):
                _target = getattr(_obj, _fn_name)
        except Exception:
            _target = None
    if _target is None and _fn_name in ns and callable(ns[_fn_name]):
        _target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
    _cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
    _user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
    if len(_user_funcs) == 1:
        _target = _user_funcs[0]
if _target is None:
    raise RuntimeError(f"Could not resolve callable '{_fn_name}'")

_raw = sys.stdin.read().strip()
if _raw:
    _parsed = json.loads(_raw)
    if isinstance(_parsed, dict):
        _kwargs = _parsed.get("kwargs", {})
        _args = _parsed.get("args", [])
    else:
        _args, _kwargs = _parsed, {}
else:
    _args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
    _args = [_args]
_res = _target(*_args, **_kwargs)
try:
    sys.stdout.write(repr(_res) + "\n")
except Exception:
    pass

```

Measured memory_bytes: 5746