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.
1#include <stdbool.h>
2
3bool checkPossibility(int* nums, int numsSize) {
4 int count = 0;
5 for (int i = 0; i < numsSize - 1; i++) {
6 if (nums[i] > nums[i + 1]) {
7 count++;
8 if (count > 1) {
9 return false;
10 }
11 if (i > 0 && nums[i + 1] < nums[i - 1]) {
12 nums[i + 1] = nums[i];
13 }
14 }
15 }
16 return true;
17}
The C solution uses a single loop to traverse the array and a counter to track violations of the non-decreasing order. If a violation is found and it's the first one, the program attempts to adjust the values strategically by evaluating neighbors.
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)
1#include
This C solution utilizes a two-pointer method to inspect boundary conditions, adjusting wrong elements while ensuring the count of such modifications doesn't exceed one. Left and right pointers indicate positions to examine simultaneously.