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 as non-decreasing if nums[i] <= nums[i + 1]
for every i
(0-based) such that (0 <= i <= n - 2).
nums = [4,2,3]
true
nums = [4,2,1]
false
n == nums.length
1 <= n <= 10^4
-10^5 <= nums[i] <= 10^5
n
is guaranteed to be at least 1.nums[i] > nums[i + 1]
.false
.nums[i] > nums[i + 1]
, decide whether to adjust nums[i]
or nums[i + 1]
based on surrounding elements.i == 0
or nums[i - 1] <= nums[i + 1]
, decrease nums[i]
.nums[i + 1]
.true
.#include <vector>
using namespace std;
bool checkPossibility(vector<int>& nums) {
int countViolations = 0;
for (int i = 0; i < nums.size() - 1; ++i) {
if (nums[i] > nums[i + 1]) {
// If already more than one modification required
if (countViolations == 1) {
return false;
}
countViolations++;
// If this is the first element, or we can adjust nums[i]
if (i == 0 || nums[i - 1] <= nums[i + 1]) {
nums[i] = nums[i + 1];
} else {
// Otherwise adjust nums[i + 1]
nums[i + 1] = nums[i];
}
}
}
return true;
}
n
is the number of elements in the input array. This is because we only traverse the array once.This approach ensures that we check the minimum number of changes needed and decide appropriately based on the current and previous elements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?