Similar Problems

Similar Problems not available

Steps To Make Array Non Decreasing - Leetcode Solution

Companies:

LeetCode:  Steps To Make Array Non Decreasing Leetcode Solution

Difficulty: Medium

Topics: stack linked-list array  

Problem:

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).

Solution:

To solve this problem, we need to loop through the entire array to check if there is any element that violates the non-decreasing property. Specifically, we need to check if nums[i] > nums[i + 1]. If there is such an element, we have two options:

  1. Decrease nums[i]. In this case, we need to check if nums[i - 1] <= nums[i]. If it is true, then the array is still non-decreasing. Otherwise, we cannot make it non-decreasing by only modifying one element.

  2. Increase nums[i + 1]. In this case, we need to check if nums[i] <= nums[i + 1]. If it is true, then the array is still non-decreasing. Otherwise, we cannot make it non-decreasing by only modifying one element.

If neither option works, then we cannot make the array non-decreasing by only modifying one element.

Here is the implementation of this algorithm in Python:

def checkPossibility(nums):
    count = 0
    for i in range(len(nums) - 1):
        if nums[i] > nums[i + 1]:
            count += 1
            if count > 1:
                return False
            if i > 0 and nums[i - 1] > nums[i + 1]:
                nums[i + 1] = nums[i]
            else:
                nums[i] = nums[i + 1]
    return True

The time complexity of this algorithm is O(n), where n is the length of the input array.

Steps To Make Array Non Decreasing Solution Code

1