Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- bool isPossible(vector<int>& nums) {
- deque<int> len;
- vector<pair<int, int>> count;
- int n=nums.size();
- // Have a list of val-count pair.
- for(int i=0; i<n; i++){
- int curVal = nums[i], cnt=0;
- while(i<n && nums[i] == curVal){
- cnt++, i++;
- }
- i--;
- count.push_back({curVal, cnt});
- }
- // Start iteration over val-count pair.
- bool possible = true;
- for(int i=0; i<count.size() && possible; i++){
- // If curVal != prevVal+1
- if(i>0 && count[i].first != count[i-1].first+1){
- while(!len.empty()){
- int curLen = len.front();
- len.pop_front();
- if(curLen < 3){
- possible = false;
- break;
- }
- }
- } // If count is greater-equal than deque length.
- else if(count[i].second >= len.size()){
- int needed = count[i].second - len.size();
- while(needed--)
- len.push_back(0);
- for(auto it=len.begin(); it!=len.end(); it++)
- (*it)++;
- } // If count is less than deque length.
- else if(count[i].second < len.size()){
- int toRemove = len.size() - count[i].second;
- while(toRemove--){
- int curLen = len.front();
- len.pop_front();
- if(curLen < 3){
- possible = false;
- break;
- }
- }
- for(auto it=len.begin(); it!=len.end(); it++)
- (*it)++;
- }
- }
- // Empty the deque.
- while(!len.empty()){
- int curLen = len.front();
- len.pop_front();
- if(curLen < 3){
- possible = false;
- break;
- }
- }
- return possible;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement