LeetCode – Non Decreasing Array

Link: https://leetcode.com/problems/non-decreasing-array/

var checkPossibility = function(nums) {
    var missMatch = 0;

    for(var i = 1; i < nums.length - 1; i++)
    {
        if (i + 1 === nums.length - 1  && nums[i + 1] < nums[i])
            missMatch++;

        if (i - 1 === 0  && nums[i - 1] > nums[i])
        {
            missMatch++;
            continue;
        }

        if (nums[i - 1] > nums[i])
        {
            missMatch++;
            
            if (nums[i - 1] > nums[i + 1] && nums[i] > nums[i + 1])
                return false;

            if (nums[i - 1] > nums[i + 1] && nums[i] < nums[i - 2])
                return false;
        }
    }

    return missMatch < 2;
};

Leave a Reply

Your email address will not be published. Required fields are marked *