-
Notifications
You must be signed in to change notification settings - Fork 0
/
084.go
84 lines (72 loc) · 1.83 KB
/
084.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package p084
/**
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given heights = [2,1,5,6,2,3],
return 10.
*/
func largestRectangleArea(heights []int) int {
if heights == nil || len(heights) == 0 {
return 0
}
heightStack := make([]int, 0)
widthStack := make([]int, 0)
stackEnd := -1
largest := -1
for i := 0; i <= len(heights); i++ {
v := -1
if i < len(heights) {
v = heights[i]
}
if v > stackEnd {
heightStack = append(heightStack, v)
widthStack = append(widthStack, 1)
stackEnd = v
} else if v == stackEnd {
widthStack[len(widthStack)-1]++
} else {
h, w := 0, 0
for len(heightStack) > 0 && heightStack[len(heightStack)-1] >= v {
//fmt.Println(heightStack, widthStack)
h = heightStack[len(heightStack)-1]
w += widthStack[len(widthStack)-1]
heightStack = heightStack[:len(heightStack)-1]
widthStack = widthStack[:len(widthStack)-1]
if h*w > largest {
largest = h * w
}
}
heightStack = append(heightStack, v)
widthStack = append(widthStack, w+1)
stackEnd = v
}
}
return largest
}
func max(a, b, c int) int {
if a >= b && a >= c {
return a
} else if b >= a && b >= c {
return b
}
return c
}
// too slow
func largestRectangleArea_Slow(heights []int) int {
if len(heights) == 0 {
return 0
} else if len(heights) == 1 {
return heights[0]
}
min := heights[0]
minIndex := 0
for i, v := range heights {
if v < min {
min = v
minIndex = i
}
}
return max(len(heights)*min, largestRectangleArea_Slow(heights[:minIndex]), largestRectangleArea_Slow(heights[minIndex+1:]))
}