imashutosh51

Non-decreasing Array

Oct 6th, 2022 (edited)
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. '''
  2. We traverse the array and look for violations: nums[i] < nums[i-1]
  3.  
  4. At a violation, there are only two possible fixes:
  5. 1. Reduce nums[i-1]
  6. 2. Increase nums[i]
  7.  
  8. We prefer to keep the smaller value unchanged if possible because smaller values are safer in a non-decreasing array and give more flexibility for upcoming elements.
  9.  
  10. So first we try to keep nums[i] unchanged (since it is smaller).
  11. To do that safely, we check:
  12.  
  13. nums[i] >= nums[i-2]
  14.  
  15. If true, then lowering nums[i-1] will still keep the left side sorted, so we do:
  16.  
  17. nums[i-1] = nums[i]
  18.  
  19. Otherwise, lowering nums[i-1] would create another violation on the left side, so we have no choice except:
  20.  
  21. nums[i] = nums[i-1]
  22. '''
  23. class Solution:
  24.     def checkPossibility(self, nums: List[int]) -> bool:
  25.         cnt=0
  26.         for i in range(1,len(nums)):
  27.             if nums[i-1]>nums[i]: #violation
  28.                 cnt+=1
  29.                 if cnt>1:
  30.                     return False
  31.                 if i<2 or nums[i-2]<=nums[i]:
  32.                     nums[i-1]=nums[i]
  33.                 else:
  34.                     nums[i]=nums[i-1]
  35.         return True
  36.        
Advertisement
Add Comment
Please, Sign In to add comment