Non-decreasing Array

Problem Id: 665 Difficulty: Medium


Intuition

Solution


class Solution:
    def checkPossibility(self, nums: List[int]) -> bool:
        if len(nums) <= 2:
            return True
        if nums[0] > nums[1]:
            nums[0] = nums[1]
        elif nums[-1] < nums[-2]:
            nums[-1] = nums[-2]
        else:
            for i in range(1, len(nums) - 1):
                if nums[i - 1] <= nums[i + 1] and not nums[i - 1] <= nums[i] <= nums[i + 1]:
                    nums[i] = nums[i - 1]
                    break

        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                return False
        return True