Skip to main content

3-14 84.柱状图中最大的矩形

Date:2022-03-13 11:04:29

标签:

  • 单调栈

题目:84.柱状图中最大的矩形 ( 困难😟 )

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

求在该柱状图中,能够勾勒出来的矩形的最大面积。

示例

示例 1:

img

输入:heights = [2,1,5,6,2,3]
输出:10
解释:最大的矩形为图中红色区域,面积为 10

示例 2:

img

输入: heights = [2,4]
输出: 4

分析

题解

function largestRectangleArea(heights: number[]): number {
const len = heights.length
const stack: {
pos: number
value: number
}[] = []
let ans = 0

if (len == 1) {
return heights[0]
}

for (let i = 0; i < len; ++i) {
const curr = heights[i]

// console.log('[stack]:', stack)

while (stack[stack.length - 1] && curr < stack[stack.length - 1].value) {
// Out of stack
const { pos } = stack.pop()
const { pos: top } = stack[stack.length - 1] ?? { pos: 0 }

const area = stack.length <= 0 ? (i - top) * heights[pos] : (i - 1 - top) * heights[pos]

ans = Math.max(ans, area)
}

stack.push({ pos: i, value: curr })
}

while (stack.length > 0) {
const { pos } = stack.pop()
const { pos: top } = stack[stack.length - 1] ?? { pos: 0 }

const area = stack.length <= 0 ? (len - top) * heights[pos] : (len - 1 - top) * heights[pos]

ans = Math.max(ans, area)
}

return ans
}

使用

function main() {
// const heights = [2, 1, 5, 6, 2, 3]
// const heights = [2, 1, 5, 6, 2] 5
// const heights = [2, 4]
// const heights = [1]
// const heights = [1, 1]
const heights = [9, 0]

console.log('[]:', largestRectangleArea(heights))
}

main()