Skip to content

Commit 64ab4a6

Browse files
committed
Runtime 175 ms (Top 75.63%) | Memory 71.0 MB (Top 50.63%)
1 parent dffb1fc commit 64ab4a6

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,32 @@
11
class Solution {
22
public:
33
int totalFruit(vector<int>& fruits) {
4-
int i=0;int j=0;int res=INT_MIN;
5-
unordered_map<int,int> mp;
4+
int i=0, j=0, ans = 1;
5+
unordered_map<int, int>mp;
66
while(j<fruits.size()){
77
mp[fruits[j]]++;
8-
if(mp.size()<=2){ // here instead of using only mp.size==2 , we are using <=2, because ,in case of input [1,1] ,here map size is <2 but we need to update result.
9-
res=max(res,j-i+1);
8+
9+
if(mp.size()<2){
10+
ans = max(ans, j-i+1);
11+
j++;
12+
}
13+
else if(mp.size()==2){
14+
ans = max(ans, j-i+1);
1015
j++;
1116
}
1217
else if(mp.size()>2){
1318
while(mp.size()>2){
1419
mp[fruits[i]]--;
15-
if(mp[fruits[i]]==0) mp.erase(fruits[i]);
20+
if(mp[fruits[i]]==0)
21+
mp.erase(fruits[i]);
1622
i++;
1723
}
24+
if(mp.size()==2){
25+
ans = max(ans, j-i+1);
26+
}
1827
j++;
1928
}
2029
}
21-
if(fruits.size()==1 && fruits[0]==0) return 1;
22-
else return res;
30+
return ans;
2331
}
2432
};

0 commit comments

Comments
 (0)