Question:

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).

Example:

  1. Input: [4,2,3]
  2. Output: True
  3. Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
  1. Input: [4,2,1]
  2. Output: False
  3. Explanation: You can't get a non-decreasing array by modify at most one element.

Solution:

  1. /**
  2. * @param {number[]} nums
  3. * @return {boolean}
  4. */
  5. var checkPossibility = function(nums) {
  6. if (nums.length === 1) return true;
  7. let count = 0;
  8. for (let i = 0; i < nums.length - 1; i++) {
  9. if (nums[i] <= nums[i+1]) continue;
  10. if (nums[i+1] - 1 < nums[i-1]) {
  11. nums[i+1] = nums[i] + 1;
  12. } else {
  13. nums[i] = nums[i+1] - 1;
  14. }
  15. count++;
  16. }
  17. return count < 2;
  18. };

Runtime: 68 ms, faster than 77.54% of JavaScript online submissions for Non-decreasing Array.