Skip to content

Commit 996126e

Browse files
committed
Non Decreasing 😐
1 parent 6c88320 commit 996126e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

β€Žnon-decreasing-array.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {boolean}
4+
*/
5+
const checkPossibility = nums => {
6+
let p = null;
7+
8+
for (let i = 0; i < nums.length - 1; i++) {
9+
if (nums[i] > nums[i + 1]) {
10+
if (p !== null) {
11+
return false;
12+
}
13+
p = i;
14+
}
15+
}
16+
17+
// array is sorted already
18+
if (p === null) {
19+
return true;
20+
}
21+
22+
// only the first and last pair need to be fixed
23+
if (p === 0 || p === nums.length - 2) {
24+
return true;
25+
}
26+
27+
// considering A[p-1], A[p], A[p+1], A[p+2]
28+
// e.g. 2, 4, 3, 5
29+
if (nums[p - 1] <= nums[p + 1]) {
30+
return true;
31+
}
32+
33+
// e.g 5, 5, 4, 6
34+
if (nums[p] <= nums[p + 2]) {
35+
return true;
36+
}
37+
38+
return false;
39+
};
40+
41+
export { checkPossibility };

0 commit comments

Comments
Β (0)