Non-decreasing Array LeetCode solution in C++

1
class Solution {
2
public:
3
bool checkPossibility(vector<int> &nums) {
4
if (nums.size() <= 2) return true;
5
// creating a diff array(size=n-1) to store differences bw 2 consecutive
6
// ele.
7
vector<int> diff(nums.size() - 1);
8
int neg = 0;
9

10
for (int i = 0; i < nums.size() - 1; i++) {
11
diff[i] = nums[i + 1] - nums[i];
12
diff[i] < 0 ? neg++ : 0; // no of negative differences
13
}
14

15
if (neg > 1) return false;
16

17
for (int i = 0; i < diff.size(); i++) {
18
if (diff[i] < 0 and i != diff.size() - 1) {
19
if (i == 0)
20
// if(diff[i+1]>=0)
21
continue; // if the first diff is neg, the next is obviosly>=0 as
22
// neg<=1, and this mountain can be resolved;
23
// else
24
// return false;
25

26
if ((nums[i - 1] <= nums[i + 1]) || (diff[i + 1]) >= abs(diff[i]))
27
continue; // the major mountain cases, lemme know below if want
28
// explaination of these
29
else
30
return false;
31
}
32
}
33
return true;
34
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0