leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0904.cpp (1264B)
0 class Solution { 1 public: 2 int totalFruit(vector<int> &fruits) { 3 pair<int, int> used = {fruits[0], -1}, count = {0, 0}, pos = {0, 0}; 4 int start = 0, res = 0; 5 6 for (start = 0; start < fruits.size(); start++) 7 if (fruits[start] != used.first) 8 break; 9 else 10 count.first++; 11 12 if (start == fruits.size()) return count.first; 13 14 used.second = fruits[start]; 15 for (int i = start; i < fruits.size(); i++) { 16 if (fruits[i] == used.first) 17 count.first++, pos.first++, pos.second = 0; 18 else if (fruits[i] == used.second) 19 count.second++, pos.first = 0, pos.second++; 20 else { 21 res = max(res, count.first + count.second); 22 if (fruits[i - 1] == used.second) { 23 used.first = fruits[i]; 24 count = pos; 25 pos = {1, 0}; 26 count.first++; 27 } else { 28 used.second = fruits[i]; 29 count = pos; 30 pos = {0, 1}; 31 count.second++; 32 } 33 } 34 } 35 36 return max(res, count.first + count.second); 37 } 38 };