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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
class Solution { public: struct basket{ int type; int number = 0; bool isempty() { return number == 0; } }; int totalFruit(vector<int>& fruits) { int maxfruits = INT32_MIN; int len = fruits.size(); int startIndex = 0, endIndex = 0; int pushElem, popElem; int newResult; basket B1, B2; for (; endIndex < len; endIndex++) { pushElem = fruits[endIndex]; if (B1.isempty() && B2.isempty()) { B1.type = pushElem; B1.number++; } else if (B1.isempty()) { if (pushElem != B2.type) { B1.type = pushElem; B1.number++; } else B2.number++; } else if (B2.isempty()) { if (pushElem != B1.type) { B2.type = pushElem; B2.number++; } else B1.number++; } else { if (pushElem == B1.type) B1.number++; else if (pushElem == B2.type) B2.number++; else { newResult = B1.number + B2.number; maxfruits = maxfruits > newResult ? maxfruits : newResult; while (!B1.isempty() && !B2.isempty()) { popElem = fruits[startIndex]; if (popElem == B1.type) B1.number--; if (popElem == B2.type) B2.number--; startIndex++; } if (B1.isempty()) { B1.type = pushElem; B1.number++; } if (B2.isempty()) { B2.type = pushElem; B2.number++; } } } } newResult = B1.number + B2.number; maxfruits = maxfruits > newResult ? maxfruits : newResult; return maxfruits; } };
class Solution { public: int totalFruit(vector<int>& fruits) { int n = fruits.size(); unordered_map<int, int> cnt;
int left = 0, ans = 0; for (int right = 0; right < n; ++right) { ++cnt[fruits[right]]; while (cnt.size() > 2) { auto it = cnt.find(fruits[left]); --it->second; if (it->second == 0) { cnt.erase(it); } ++left; } ans = max(ans, right - left + 1); } return ans; } };
|