Iam_Sandeep

665. Non-decreasing Array

Jul 26th, 2022
822
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. '''
  2. Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.
  3.  
  4. 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).
  5.  
  6.  
  7. '''
  8. '''
  9. #Here consider case 2,2,1
  10.  
  11. if we just check pairs and when we find inflection point(violate increasing) if we change inflection point to right most
  12. element like here inflection happens at index 1 and if we change it becomes [2,1, 1] which is not sorted.
  13. So we should instead pass present element to next element [2,2,2] (when you dont have choice of nums[i-1]<=nums[i+1] ) .
  14. See code for clarity with this example.
  15. '''
  16. class Solution:
  17.     def checkPossibility(self, nums: List[int]) -> bool:
  18.         n=len(nums)
  19.         change=False
  20.         for i in range(n-1):
  21.             if nums[i]<=nums[i+1]:
  22.                 continue
  23.            
  24.             if change==True:
  25.                 return False
  26.        
  27.             if i==0 or nums[i-1]<=nums[i+1]:
  28.                 nums[i]=nums[i+1]
  29.             else:
  30.                 nums[i+1]=nums[i]
  31.             change=True
  32.         return True
  33.            
Advertisement
Add Comment
Please, Sign In to add comment