class Solution {
public boolean checkPossibility(int[] nums) {
int n = nums.length, count = 0;
for (int i = 0; i + 1 < n; i++) {
if (nums[i] > nums[i + 1]) {
count++;
if (i > 0 && nums[i + 1] < nums[i  1]) nums[i + 1] = nums[i];
else nums[i] = nums[i + 1];
}
}
return count <= 1;
}
}
Java solution, 7 liner.


@BatCoder I think
if
condition checksi > 0
first, ifi == 0
then the rest part will not be checked



@AllegroLeonLi You are right. It can be done without that
else
part as well. The solution gets accepted without it.

agree,
and it can be even faster:public boolean checkPossibility(int[] nums) {
int n = nums.length, count = 0;for (int i = 0; i + 1 < n; i++) { if (nums[i] > nums[i + 1]) { count++; if(count == 2) { return false; } if (i > 0 && nums[i + 1] < nums[i  1]) nums[i + 1] = nums[i]; //else nums[i] = nums[i + 1]; } } return count <= 1; }

The solution without modifying the input array based on your post
class Solution { public boolean checkPossibility(int[] nums) { if (nums.length == 0) { return true; } for (int i = 0, cur = nums[0], count = 0; i < nums.length  1; i++) { if (cur > nums[i + 1]) { if (count == 1) { return false; } if (!(i > 0 && nums[i  1] > nums[i + 1])) { cur = nums[i + 1]; } count++; } else { cur = nums[i + 1]; } } return true; } }