# 904 - Fruit Into Baskets

## 解法一 - Sliding window

``````class Solution {
public:
int totalFruit(vector<int>& tree) {
int maxLength = 0;

unordered_map<int, int> table;
int windowStart = 0;

for(int windowEnd = 0; windowEnd<tree.size(); windowEnd++) {
table[tree[windowEnd]]++;

while(table.size() > 2) {
if(--table[tree[windowStart]] == 0)
table.erase(tree[windowStart]);
windowStart++;
}

// Compare maxLength after assuring there are less
// than 2 diff. fruit type
maxLength = max(maxLength, windowEnd-windowStart+1);
}

return maxLength;
}
};
``````

``````if(table.size() <= 2) {
maxLength = max(maxLength, windowEnd-windowStart+1);
}
``````

``````class Solution {
public:
int totalFruit(vector<int>& tree) {
int maxLength = 0;

unordered_map<char, int> table;
int windowStart = 0;

for(int windowEnd = 0; windowEnd<tree.size(); windowEnd++) {
table[tree[windowEnd]]++;

if(table.size() <= 2) {
maxLength = max(maxLength, windowEnd-windowStart+1);
}

while(table.size() > 2) {
if(--table[tree[windowStart]] == 0)
table.erase(tree[windowStart]);
windowStart++;
}
}

return maxLength;
}
};
``````