665. Non-decreasing Array (Array 1)

 

https://leetcode.com/problems/non-decreasing-array/


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
    def checkPossibility(self, nums: List[int]) -> bool:
        if len(nums) < 3:
            return True

        chance = 1
        for i in range(len(nums)-2):
            a, b, c = nums[i:i+3]

            if (a <= b <= c):
                continue
            elif (a > b > c):
                return False
            else:
                if chance == 0:
                    return False
                chance -= 1
                if (a <= b) and (b > c):
                    if a <= c:
                        nums[i+1] = nums[i+2]
                    else:
                        nums[i+2] = nums[i+1]
                elif (a > b) and (b <= c):
                    if a <= c:
                        nums[i+1] = nums[i+2]
                    else:
                        nums[i] = nums[i+1]
        return True

Complexity

$O(|\text{nums}|)$