C++ O(n) - count invalid sequence


  • 0
    T
    class Solution {
    public:
        bool checkPossibility(vector<int>& nums) {
            int cnt =0;
            for(int i =0; (i+1)<nums.size();i++)
            {
                if(nums[i]>nums[i+1]) 
                {
                    cnt++;
                    if(cnt>=2) return false;
                    if(i==0 || nums[i-1]<=nums[i+1]) nums[i]=nums[i+1]; // Special case for the first element(no element exists before pos i)
                    else nums[i+1]=nums[i];
                }
            }
            return true;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.