Sponsored
Sponsored
This approach makes a single pass through the array while keeping a count of occurrences where nums[i] > nums[i+1]. If more than one such occurrence is found, it returns false. During the traversal, if such an occurrence is found, we will attempt to resolve it by modifying nums[i] or nums[i+1] optimally based on their neighbors.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1), since no additional space is used dependent on input size.
1public class Solution {
2 public bool CheckPossibility(int[] nums) {
3 int count = 0;
4 for (int i = 0; i < nums.Length - 1; i++) {
5 if (nums[i] > nums[i + 1]) {
6 count++;
7 if (count > 1) return false;
8 if (i > 0 && nums[i + 1] < nums[i - 1]) {
9 nums[i + 1] = nums[i];
10 }
11 }
12 }
13 return true;
14 }
15}
The C# solution leverages a loop with a condition counter to iterate through the input. It modifies one element if needed and possible to uphold the non-decreasing condition, making the smallest effective adjustment.
This approach involves using two pointers to traverse from the start and end of the array. We simulate potential changes to resolve any issues at both ends, using the pointers to converge inwards and analyze changes required to achieve a non-decreasing state.
Time Complexity: O(n)
Space Complexity: O(1)
1var
The JavaScript solution applies the two-pointer method to strategically modify or skip problem elements from both array ends, ensuring optimal use of the single modification allowance.