665. Non-decreasing Array #
Problem #
Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
Example 1:
Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: nums = [4,2,1]
Output: false
Explanation: You can't get a non-decreasing array by modify at most one element.
Constraints:
n == nums.length1 <= n <= 104-10^5 <= nums[i] <= 10^5
Problem Summary #
Given an integer array of length n, determine whether the array can become a non-decreasing sequence by changing at most 1 element. We define a non-decreasing sequence as follows: for any i (0 <= i <= n-2) in the array, nums[i] <= nums[i + 1] is always satisfied.
Solution Approach #
- Easy problem. Loop through the array and find decreasing pairs where
nums[i] > nums[i+1]. Once there are more than 2 such pairs, return false directly. When the first decreasing pair is found, one manual adjustment is needed. Ifnums[i + 1] < nums[i - 1], then even ifnums[i+1]andnums[i]are swapped, after the swap,nums[i - 1]may still be greater thannums[i + 1], which does not satisfy the requirement. The correct approach should be to make the smaller number larger, namelynums[i + 1] = nums[i]. Two equal elements satisfy the requirement of being non-decreasing.
Code #
package leetcode
func checkPossibility(nums []int) bool {
count := 0
for i := 0; i < len(nums)-1; i++ {
if nums[i] > nums[i+1] {
count++
if count > 1 {
return false
}
if i > 0 && nums[i+1] < nums[i-1] {
nums[i+1] = nums[i]
}
}
}
return true
}