Pregunta de entrevista de Zalando
Given an array with n integers, check if it could become non-decreasing by removing at most 1 element.
Example:
Input: [3,2,4,3], Output: false
Input:[1, 4, 2, 3], Output: true
Input:[4, 3, 2], Output: false
Input:[1, 2, 3], Output: true
Respuestas de entrevistas
could use a monotonic stack and can be solved in O(n)
public boolean checkPossibility(int[] nums) {
int l = nums.length, cnt = 0;
for (int i = 0; i nums[i + 1]) { // e.g. [2,2,3,2,4] 3>2
if (i > 0) {
if (nums[i - 1] <= nums[i + 1]) // if number is lesser or equal modify nums[i]
nums[i] = nums[i - 1]; // to the previous number. 2<=2 modify nums[i] =2
else // in all other cases modify the next number
nums[i + 1] = nums[i]; // to the current number to match// the sequence
}
++cnt;
}
}
return cnt <= 1;
}