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:
Input: [4,2,3]Output: TrueExplanation: You could modify the first 4 to 1 to get a non-decreasing array.
Input: [4,2,1]Output: FalseExplanation: You can't get a non-decreasing array by modify at most one element.
Solution:
/*** @param {number[]} nums* @return {boolean}*/var checkPossibility = function(nums) {if (nums.length === 1) return true;let count = 0;for (let i = 0; i < nums.length - 1; i++) {if (nums[i] <= nums[i+1]) continue;if (nums[i+1] - 1 < nums[i-1]) {nums[i+1] = nums[i] + 1;} else {nums[i] = nums[i+1] - 1;}count++;}return count < 2;};
Runtime: 68 ms, faster than 77.54% of JavaScript online submissions for Non-decreasing Array.
