[LeetCode] Non-decreasing Array

665. Non-decreasing Array

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool checkPossibility(vector<int>& nums) {
int check(0);
for(int i = 1; i < nums.size() and check < 2; ++i) {
if(nums[i - 1] > nums[i]) {
++check;
(i < 2 or nums[i - 2] <= nums[i]) ? (nums[i - 1] = nums[i]) : (nums[i] = nums[i - 1]);
}
}
return check < 2;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/14/PS/LeetCode/non-decreasing-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.