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.


Note: Although I got the main idea, it took me a while to get the conditions right.
And had to look up the solution.

def checkPossibility_Myalgo(nums: List[int]):
    L = len(nums)        
    usedMod = False
   
    for i in range(L-1):
        if nums[i+1] < nums[i]:
            if usedMod:
                return False                
            if i != 0 and i != L-2 and nums[i-1] > nums[i+1] and nums[i] > nums[i+2]:
                return False
            usedMod = True                        
    return True
   
def checkPossibility_bit_cleaner(nums: List[int]):
           
    L = len(nums)        
    p = None
   
    for i in range(L-1):
        if nums[i+1] < nums[i]:
            if p is not None:
                return False                
            p = i
                   
    return  p is None or p == 0 or p == L-2 \
            or nums[p-1] <= nums[p+1] or nums[p] <= nums[p+2]

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break