84. Largest Rectangle in Histogram (Solution 1)

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
    }
}

 

posted @ 2020-08-23 10:54  johnny_zhao  阅读(94)  评论(0编辑  收藏  举报