File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments