Advertisement
nikunjsoni

659

May 24th, 2021
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool isPossible(vector<int>& nums) {
  4.         deque<int> len;
  5.         vector<pair<int, int>> count;
  6.         int n=nums.size();
  7.        
  8.         // Have a list of val-count pair.
  9.         for(int i=0; i<n; i++){
  10.             int curVal = nums[i], cnt=0;
  11.             while(i<n && nums[i] == curVal){
  12.                 cnt++, i++;
  13.             }
  14.             i--;
  15.             count.push_back({curVal, cnt});
  16.         }
  17.        
  18.         // Start iteration over val-count pair.
  19.         bool possible = true;
  20.         for(int i=0; i<count.size() && possible; i++){
  21.             // If curVal != prevVal+1
  22.             if(i>0 && count[i].first != count[i-1].first+1){
  23.                 while(!len.empty()){
  24.                     int curLen = len.front();
  25.                     len.pop_front();
  26.                     if(curLen < 3){
  27.                         possible = false;
  28.                         break;
  29.                     }
  30.                 }
  31.             } // If count is greater-equal than deque length.
  32.             else if(count[i].second >= len.size()){
  33.                 int needed = count[i].second - len.size();
  34.                 while(needed--)
  35.                     len.push_back(0);
  36.                 for(auto it=len.begin(); it!=len.end(); it++)
  37.                     (*it)++;
  38.             } // If count is less than deque length.
  39.             else if(count[i].second < len.size()){
  40.                 int toRemove = len.size() - count[i].second;
  41.                 while(toRemove--){
  42.                     int curLen = len.front();
  43.                     len.pop_front();
  44.                     if(curLen < 3){
  45.                         possible = false;
  46.                         break;
  47.                     }
  48.                 }
  49.                 for(auto it=len.begin(); it!=len.end(); it++)
  50.                     (*it)++;
  51.             }
  52.         }
  53.        
  54.         // Empty the deque.
  55.         while(!len.empty()){
  56.             int curLen = len.front();
  57.             len.pop_front();
  58.             if(curLen < 3){
  59.                 possible = false;
  60.                 break;
  61.             }
  62.         }
  63.         return possible;
  64.     }
  65. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement