Skip to content

Commit 57cbf35

Browse files
authored
Create steps-to-make-array-non-decreasing.py
1 parent d614b44 commit 57cbf35

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# mono stack, dp
5+
class Solution(object):
6+
def totalSteps(self, nums):
7+
"""
8+
:type nums: List[int]
9+
:rtype: int
10+
"""
11+
dp = [0]*len(nums) # dp[i]: number of rounds for a[i] to remove all the covered elements
12+
stk = []
13+
for i in reversed(xrange(len(nums))):
14+
while stk and nums[stk[-1]] < nums[i]:
15+
dp[i] = max(dp[i]+1, dp[stk.pop()])
16+
stk.append(i)
17+
return max(dp)
18+
19+
20+
# Time: O(n)
21+
# Space: O(n)
22+
# mono stack, dp
23+
class Solution2(object):
24+
def totalSteps(self, nums):
25+
"""
26+
:type nums: List[int]
27+
:rtype: int
28+
"""
29+
dp = [0]*len(nums) # dp[i]: number of rounds for a[i] to be removed
30+
stk = []
31+
for i in xrange(len(nums)):
32+
curr = 0
33+
while stk and nums[stk[-1]] <= nums[i]:
34+
curr = max(curr, dp[stk.pop()])
35+
if stk:
36+
dp[i] = curr+1
37+
stk.append(i)
38+
return max(dp)

0 commit comments

Comments
 (0)