var maximalRectangle = function (matrix) {
let max = 0
if (matrix.length === 0) {
return 0
}
let heights = new Array(matrix[0].length)
for (let r = 0; r < matrix.length; r++) {
let row = matrix[r]
for (let c = 0; c < row.length; c++) {
let item = row[c]
if (item === '1') {
if (heights[c]) {
heights[c]++
} else {
heights[c] = 1
}
} else {
heights[c] = 0
}
}
max = Math.max(largestRectangleArea(heights), max)
}
return max
};
var largestRectangleArea = function (heights) {
const stack = []
let max = 0
let i = 0
while (i < heights.length) {
if (stack.length === 0) {
stack.push(i)
i++
} else {
let topIndex = stack[stack.length - 1]
let cur = heights[i]
// 如果當(dāng)前元素高 大于等于 棧頂元素的高; 直接入棧, 否則需要計(jì)算面積
if (cur >= heights[topIndex]) {
stack.push(i)
i++
} else {
// 拿到棧頂元素, 同時(shí)將棧頂?shù)脑?pop 出棧
let topH = heights[stack.pop()]
// 查看新棧頂下標(biāo)的
let newTop = stack.length === 0 ? -1 : stack[stack.length - 1]
// 當(dāng)前的 下標(biāo) i
let area = (i - newTop - 1) * topH
max = Math.max(max, area)
}
}
}
while (stack.length !== 0) {
let topH = heights[stack.pop()]
let newTop = stack.length === 0 ? -1 : stack[stack.length - 1]
let w = heights.length
let area = (w - (newTop + 1)) * topH
max = Math.max(max, area)
}
return max
};
const r = maximalRectangle([
["1", "0", "1", "0", "0"],
["1", "0", "1", "1", "1"],
["1", "1", "1", "1", "1"],
["1", "0", "0", "1", "0"]
])
console.log(r)
最大矩形: (85號(hào))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 題目鏈接 tag: Hard; question:??Given a 2D binary matrix fille...
- 題目鏈接難度:困難 類型:動(dòng)態(tài)規(guī)劃 給定一個(gè)僅包含 0 和 1 的二維二進(jìn)制矩陣,找出只包含 1...
- 給定一個(gè)僅包含 0 和 1 的二維二進(jìn)制矩陣,找出只包含 1 的最大矩形,并返回其面積。 思路: 每一行計(jì)算高度,...