首页 > 其他 > 详细

84. Largest Rectangle in Histogram (Solution 1)

时间:2020-08-23 14:11:26      阅读:51      评论:0      收藏:0      [点我收藏+]
package LeetCode_84

/**
 * 84. Largest Rectangle in Histogram
 * https://leetcode.com/problems/largest-rectangle-in-histogram/description/
 *
 * 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.
 * */
class Solution {
    /*
    *solution 1: brute force, Time complexity:O(n^2), Space complexity:O(1)
    * */
    fun largestRectangleArea(heights: IntArray): Int {
        var res = 0
        val n = heights.size
        for (i in 0 until n) {
            var minH = heights[i]
            //keep tracking it left hand side, find out the minimum height to calculate area
            for (j in i downTo 0) {
                minH = Math.min(minH, heights[j])
                //area = width * min_height
                val area = minH * (i - j + 1)
                res = Math.max(area, res)
            }
        }
        return res
    }
}

 

84. Largest Rectangle in Histogram (Solution 1)

原文:https://www.cnblogs.com/johnnyzhao/p/13548548.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!