LeetCode //C - 665. Non-decreasing Array

665. Non-decreasing Array

Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.

We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
 

Example 1:

Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: nums = [4,2,1]
Output: false
Explanation: You cannot get a non-decreasing array by modifying at most one element.

Constraints:
  • n == nums.length
  • 1 < = n < = 1 0 4 1 <= n <= 10^4 1<=n<=104
  • − 1 0 5 < = n u m s [ i ] < = 1 0 5 -10^5 <= nums[i] <= 10^5 105<=nums[i]<=105

From: LeetCode
Link: 665. Non-decreasing Array


Solution:

Ideas:
  • The loop detects any pair where nums[i] > nums[i+1].
  • If this happens more than once, we return false.
  • When there’s a violation, we choose the safer element to modify based on the neighbors.
Code:
bool checkPossibility(int* nums, int numsSize) {
    int count = 0; // count the number of modifications
    
    for (int i = 0; i < numsSize - 1; i++) {
        if (nums[i] > nums[i + 1]) {
            if (++count > 1) {
                return false; // more than one modification needed
            }
            
            // Modify nums[i] or nums[i + 1] based on surrounding values
            if (i == 0 || nums[i - 1] <= nums[i + 1]) {
                nums[i] = nums[i + 1]; // modify nums[i]
            } else {
                nums[i + 1] = nums[i]; // modify nums[i + 1]
            }
        }
    }
    
    return true;
}

你可能感兴趣的:(LeetCode,leetcode,c语言,算法)