LeetCode 904. Fruit Into Baskets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int totalFruit(vector<int>& fruits) {
int n = fruits.size(), ans = 0;
vector<int> freq(n);
for (int left = 0, right = 0, cnt = 0; right < n; ++right) {
if (++freq[fruits[right]] == 1) ++cnt;
while (cnt > 2)
if (--freq[fruits[left++]] == 0) --cnt;
ans = max(ans, right - left + 1);
}
return ans;
}
};