class Solution {
public:
    int totalFruit(vector<int>& tree) {
        map<int, int> idx; // {fruit -> last_index}
        int ans = 0;
        int cur = 0;
        for (int i = 0; i < tree.size(); ++i) {
            int f = tree[i];
            if (!idx.count(f)) {
                if (idx.size() == 2) {
                    auto it1 = begin(idx);
                    auto it2 = next(it1);
                    if (it1->second > it2->second) swap(it1, it2);
                    cur = i - it1->second - 1;
                    idx.erase(it1);
                }
            }
            idx[f] = i;
            ans = max(++cur, ans);
        }
        return ans;
    }
};

@@ -1,8 +1,401 @@
+// Solution: Hashtable + Sliding window%0A// Time complexity: O(n)%0A// Space complexity: O(1)%0A// Keep track of the last index of each element. If a third type of fruit comes in, the new window starts after the fruit with smaller last index. Otherwise extend the current window.%0A// %5B1 3 1 3 1 1%5D 4 1 4 ... %3C- org window, 3 has a smaller last index than 1.%0A// 1 3 1 3 %5B1 1 4%5D 1 4 ... %3C- new window%0A
 class So
@@ -407,19 +407,18 @@
 n %7B%0A
+    
 public
-:%0A   
  int
@@ -433,20 +433,13 @@
 uit(
-vector%3C
 int
-%3E&
+%5B%5D
  tre
@@ -455,25 +455,55 @@
     
-map%3Ci
+TreeMap%3CI
 nt
+eger
 , 
-i
+I
 nt
+eger
 %3E idx
+ = new TreeMap%3C%3E()
 ; //
@@ -600,22 +600,22 @@
  %3C tree.
-size()
+length
 ; ++i) %7B
@@ -671,11 +671,17 @@
 x.co
-u
 nt
+ainsKey
 (f))
@@ -746,140 +746,345 @@
     
-auto it1 = begin(idx);%0A                    auto it2 = next(it1);%0A                    if (it1-%3Esecond %3E it2-%3Esecond) swap(it1,
+Map.Entry%3CInteger, Integer%3E it1 = idx.firstEntry();%0A                    Map.Entry%3CInteger, Integer%3E it2 = idx.lastEntry();%0A                    if (it1.getValue() %3E it2.getValue()) %7B%0A                        Map.Entry%3CInteger, Integer%3E tmp = it1;%0A                        it1 =
  it2
-)
 ;%0A
+                        it2 = tmp;%0A                    %7D%0A
     
@@ -1116,16 +1116,19 @@
  it1
--%3Esecond
+.getValue()
  - 1
@@ -1157,17 +1157,27 @@
 idx.
-erase(it1
+remove(it1.getKey()
 );%0A 
@@ -1226,15 +1226,24 @@
  idx
-%5Bf%5D =
+.put(tree%5Bi%5D,
  i
+)
 ;%0A  
@@ -1258,16 +1258,21 @@
   ans = 
+Math.
 max(++cu
@@ -1317,10 +1317,9 @@
 %0A    %7D%0A%7D
-;
 %0A

add FruitIntoBaskets.java