-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob0084.go
60 lines (51 loc) · 1.1 KB
/
prob0084.go
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package prob0084
type StackInt struct {
Data []int
}
func (s *StackInt) Top() int {
if len(s.Data) == 0 {
return 0
}
return s.Data[len(s.Data)-1]
}
func (s *StackInt) Push(i int) {
s.Data = append(s.Data, i)
}
func (s *StackInt) Pop() {
if len(s.Data) == 0 {
}
s.Data = s.Data[0 : len(s.Data)-1]
}
func (s *StackInt) IsEmpty() bool {
return len(s.Data) == 0
}
func NewStackInt() *StackInt {
return &StackInt{
Data: []int{},
}
}
func largestRectangleArea(heights []int) int {
incresStask := NewStackInt()
// 最后结算
heights = append(heights, 0)
res := 0
for i, h := range heights {
for !incresStask.IsEmpty() && heights[incresStask.Top()] > h {
popIndex := incresStask.Top()
popH := heights[popIndex]
incresStask.Pop()
beginIndex := -1
if !incresStask.IsEmpty() {
beginIndex = incresStask.Top()
}
// 要找到前一个入栈元素的index,因为中间的元素都比 popH 大
// 示意图:http://data3.liuin.cn/2021_01_30_19_35_09_7xWEYilt.png
w := i - beginIndex - 1
if popH*w > res {
res = popH * w
}
}
incresStask.Push(i)
}
return res
}