728x90
https://leetcode.com/problems/non-decreasing-array/
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
changed = False
for i in range(len(nums) - 1):
if nums[i] <= nums[i+1]:
continue
if changed:
return False
# We want to decrease left element , if possible
if i == 0 or nums[i+1] >= nums[i-1]:
nums[i] = nums[i+1]
else:
nums[i+1] = nums[i]
changed = True
return True
when considering pair, we can either adjust left element to be same as right one or adjust right element to be same as left element.
we chose to do left adjustment. only if i-1 is less than i+1 , otherwise it would ruin previous non decreasing order
728x90
'Algorithm > NeetCode' 카테고리의 다른 글
Number of Zero-Filled Subarrays (0) | 2024.11.13 |
---|---|
First Missing Positive (1) | 2024.11.12 |
Range Sum Query 2D - Immutable (0) | 2024.11.10 |
Check If a String Contains All Binary Codes of Size K (0) | 2024.11.09 |
Insert Delete GetRandom O(1) (0) | 2024.11.08 |