Simple Python solution


  • 3

    The logic is to first find any inversions, and if the number of inversions is > 1, then we need to modify more than 1 element and hence we return False.

    Once we find an inversion,

    We have to fix either the current value or the next value appropriately so that any future inversions can be detected correctly.

    def checkPossibility(self, nums):
        count_dec = 0
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                count_dec += 1
                if i == 0:
                    nums[i] = nums[i + 1]
                elif nums[i - 1] <= nums[i + 1]:
                    nums[i] = nums[i - 1]
                else:
                    nums[i + 1] = nums[i]
            if count_dec > 1:
                return False
        return True
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.