1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: int totalFruit(vector<int>& fruits) { int left=0,right=0; int n=fruits.size(); int max_fruit=INT_MIN; unordered_map<int,int> basket; for(int i = 0 ; i<n;i++){ int fruit_num= fruits[i]; basket[fruit_num]++; while(basket.size()>2){ int fruit_num=fruits[left]; basket[fruit_num]--; if(basket[fruit_num]==0){ basket.erase(fruit_num); } left++; } max_fruit=max_fruit>i-left+1?max_fruit:i-left+1; } return max_fruit; } };
|