Skip to content

Commit cabfa87

Browse files
authored
Create non-decreasing-array.py
1 parent f76eab0 commit cabfa87

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Python/non-decreasing-array.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# Given an array with n integers, your task is to check if
5+
# it could become non-decreasing by modifying at most 1 element.
6+
#
7+
# We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).
8+
#
9+
# Example 1:
10+
# Input: [4,2,3]
11+
# Output: True
12+
# Explanation: You could modify the first
13+
# 4
14+
# to
15+
# 1
16+
# to get a non-decreasing array.
17+
# Example 2:
18+
# Input: [4,2,1]
19+
# Output: False
20+
# Explanation: You can't get a non-decreasing array by modify at most one element.
21+
# Note: The n belongs to [1, 10,000].
22+
23+
class Solution(object):
24+
def checkPossibility(self, nums):
25+
"""
26+
:type nums: List[int]
27+
:rtype: bool
28+
"""
29+
modified, prev = False, nums[0]
30+
for i in xrange(1, len(nums)):
31+
if prev > nums[i]:
32+
if modified:
33+
return False
34+
if i-2 < 0 or nums[i-2] <= nums[i]:
35+
prev = nums[i] # nums[i-1] = nums[i], prev = nums[i]
36+
else:
37+
prev = nums[i-1] # nums[i] = nums[i-1], prev = nums[i]
38+
modified = True
39+
else:
40+
prev = nums[i]
41+
return True
42+

0 commit comments

Comments
 (0)