(Js) Leetcode 665. Non-decreasing sequence

topic:

Here is an integer array of length n. Please judge whether the array can be turned into a non-decreasing sequence when one element is changed at most.

We define a non-decreasing sequence like this: For any i (0 <= i <= n-2) in the array, nums[i] <= nums[i + 1] is always satisfied.

Example 1:

Input: nums = [4,2,3]
Output: true
Explanation: You can make it a non-decreasing sequence by changing the first 4 to 1.
Example 2:

Input: nums = [4,2,1]
Output: false
Explanation: You cannot change one element to a non-decreasing sequence.

Code:

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var checkPossibility = function (nums) {
    const n = nums.length;
    let cnt = 0;
    for (let i = 0; i < n - 1; ++i) {
        const x = nums[i], y = nums[i + 1];
        if (x > y) {
            cnt++;
            if (cnt > 1) {
                return false;
            }
            if (i > 0 && y < nums[i - 1]) {
                nums[i + 1] = x;
            }
        }
    }
    return true;
};

operation result:

Guess you like

Origin blog.csdn.net/M_Eve/article/details/113925659