forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsteps-to-make-array-non-decreasing.py
More file actions
38 lines (35 loc) · 1 KB
/
steps-to-make-array-non-decreasing.py
File metadata and controls
38 lines (35 loc) · 1 KB
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
29
30
31
32
33
34
35
36
37
38
# Time: O(n)
# Space: O(n)
# mono stack, dp
class Solution(object):
def totalSteps(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0]*len(nums) # dp[i]: number of rounds for nums[i] to remove all the covered elements
stk = []
for i in reversed(xrange(len(nums))):
while stk and nums[stk[-1]] < nums[i]:
dp[i] = max(dp[i]+1, dp[stk.pop()])
stk.append(i)
return max(dp)
# Time: O(n)
# Space: O(n)
# mono stack, dp
class Solution2(object):
def totalSteps(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0]*len(nums) # dp[i]: number of rounds for nums[i] to be removed
stk = []
for i in xrange(len(nums)):
curr = 0
while stk and nums[stk[-1]] <= nums[i]:
curr = max(curr, dp[stk.pop()])
if stk:
dp[i] = curr+1
stk.append(i)
return max(dp)