leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0904.cpp (1264B)


      1 class Solution {
      2   public:
      3     int totalFruit(vector<int> &fruits) {
      4         pair<int, int> used = {fruits[0], -1}, count = {0, 0}, pos = {0, 0};
      5         int start = 0, res = 0;
      6 
      7         for (start = 0; start < fruits.size(); start++)
      8             if (fruits[start] != used.first)
      9                 break;
     10             else
     11                 count.first++;
     12 
     13         if (start == fruits.size()) return count.first;
     14 
     15         used.second = fruits[start];
     16         for (int i = start; i < fruits.size(); i++) {
     17             if (fruits[i] == used.first)
     18                 count.first++, pos.first++, pos.second = 0;
     19             else if (fruits[i] == used.second)
     20                 count.second++, pos.first = 0, pos.second++;
     21             else {
     22                 res = max(res, count.first + count.second);
     23                 if (fruits[i - 1] == used.second) {
     24                     used.first = fruits[i];
     25                     count = pos;
     26                     pos = {1, 0};
     27                     count.first++;
     28                 } else {
     29                     used.second = fruits[i];
     30                     count = pos;
     31                     pos = {0, 1};
     32                     count.second++;
     33                 }
     34             }
     35         }
     36 
     37         return max(res, count.first + count.second);
     38     }
     39 };