-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0904-fruit-into-baskets.cpp
More file actions
35 lines (35 loc) · 1.02 KB
/
0904-fruit-into-baskets.cpp
File metadata and controls
35 lines (35 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
int totalFruit(vector<int>& fruits) {
int n = (int)fruits.size();
int l = 0, res = 0;
int f1 = -1, f2 = -1;
int f1_cnt = 0, f2_cnt = 0;
for (int r = 0; r < n; r++) {
if (f1 == -1 || f1 == fruits[r]) {
f1 = fruits[r];
f1_cnt++;
} else if (f2 == -1 || f2 == fruits[r]) {
f2 = fruits[r];
f2_cnt++;
} else {
while (f2_cnt > 0 && f1_cnt > 0 && l < r) {
if (fruits[l] == f1) f1_cnt--;
else if (fruits[l] == f2) f2_cnt--;
else assert(false);
l++;
}
if (f1_cnt == 0) {
f1 = fruits[r];
f1_cnt++;
}
else {
f2 = fruits[r];
f2_cnt++;
}
}
res = max(res, r - l + 1);
}
return res;
}
};