You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
* Follow**Monotonic Stack**'s common rule:**only calculating when`pop()` is happening**. This common rule can be applied to calculating result for**most** of the`Monotonic Stack` problems.
34
-
*Disappeared heights (popped by`current_height` or popped by`stack_top_height`)areall taller than`stack_top_height`. This logic will be used to calculate the`width`.
34
+
*To calculate the`width`, therearetwo ways:
35
35
36
-
Detailed solutions will be given later, and now only the best practices in 7 languages are given.
36
+
###Way 1
37
+
* The last`popped_index` from stack should be kept since we need it to calculate the`width`.
38
+
39
+
###Way 2
40
+
* Disappeared heights (popped when`current_height < stack_top_height`) are all taller than`stack_top_height`. This logic will be used to calculate the`width`.
while index_stackand height< heights[index_stack[-1]]:
52
82
popped_index= index_stack.pop()
53
83
54
84
popped_height= heights[popped_index]
55
85
56
-
left_index= index_stack[-1]# popped_height's remaining left heights are all shorter than 'popped_height', because when 'popped_height' itself was pushed into stack, it must have caused some (could be none) taller heights been popped out of the stack.
57
-
right_index= i# popped_height's right heights (which are all taller than 'popped_height') have been popped out of the stack (disappeared) when current `i` height is being pushed into stack.
58
-
width= right_index- left_index-1# So in the range of 'width', they are all no shorter than `popped_height`, although they have been popped out of the stack (disappeared).
86
+
left_index= index_stack[-1]#Different from way 1.popped_height's remaining left heights are all shorter than 'popped_height', because when 'popped_height' itself was pushed into stack, it must have caused some (could be none) taller heights been popped out of the stack.
87
+
right_index= i#Different from way 1.popped_height's right heights (which are all taller than 'popped_height') have been popped out of the stack (disappeared) when current `i` height is being pushed into stack.
88
+
width= right_index- left_index-1#Different from way 1.So in the range of 'width', they are all no shorter than `popped_height`, although they have been popped out of the stack (disappeared).