Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.
- 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).
- '''
- '''
- #Here consider case 2,2,1
- if we just check pairs and when we find inflection point(violate increasing) if we change inflection point to right most
- element like here inflection happens at index 1 and if we change it becomes [2,1, 1] which is not sorted.
- 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] ) .
- See code for clarity with this example.
- '''
- class Solution:
- def checkPossibility(self, nums: List[int]) -> bool:
- n=len(nums)
- change=False
- for i in range(n-1):
- if nums[i]<=nums[i+1]:
- continue
- if change==True:
- return False
- if i==0 or nums[i-1]<=nums[i+1]:
- nums[i]=nums[i+1]
- else:
- nums[i+1]=nums[i]
- change=True
- return True
Advertisement
Add Comment
Please, Sign In to add comment