-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path904.cpp
More file actions
48 lines (43 loc) · 1.16 KB
/
904.cpp
File metadata and controls
48 lines (43 loc) · 1.16 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
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
int totalFruit(vector<int>& fruits) {
int first = fruits[0];
int ind1 = 0;
int second = -1;
int ind2 = -1;
int cur = 1;
int total = 1;
int i = 1;
for(i = 1; i < fruits.size(); i++){
cur++;
total++;
if(fruits[i] != first){
second = fruits[i];
ind2 = i;
break;
}
}
i++;
for(i; i < fruits.size(); i++){
if(fruits[i] == first){
if(ind1 < ind2) ind1 = i;
cur++;
total = max(total, cur);
continue;
}
if(fruits[i] == second){
if(ind2 < ind1) ind2 = i;
cur++;
total = max(total, cur);
continue;
}
total = max(total, cur);
cur = i - max(ind1, ind2) + 1;
second = (ind1 > ind2 ? first : second);
ind2 = max(ind1, ind2);
first = fruits[i];
ind1 = i;
}
return total;
}
};