LeetCode 84 Largest Rectangle in Histrogram (C++, Python)

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.
For example,
Given height = [2,1,5,6,2,3],
return 10.


Solution C++


 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
class Solution {
public:
    int largestRectangleArea(vector<int>& height) {
        if (height.empty()) return 0;
        int size = height.size();
        int left[size];
        int right[size];
        for (int i = 0; i < size; ++i) {
            int j = i;
            while (j > 0 && height[i] <= height[j - 1]) {
                j = left[j - 1];
            }
            left[i] = j;
        }
        for (int i = size- 1; i >=0; --i) {
            int j = i;
            while (j < size- 1 && height[i] <= height[j + 1]) {
                j = right[j + 1];
            }
            right[i] = j;
        }
        int area = 0;
        for (int i = 0; i < size; ++i) {
            area = max(area, height[i] * (right[i] - left[i] + 1));
        }
        return area;
    }
};

Solution Python


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
    # @param {integer[]} height
    # @return {integer}
    def largestRectangleArea(self, height):
        height.append(0)
        i = 0;
        increStack = []
        area = 0
        while i < len(height):
            if not increStack or height[i] > height[increStack[-1]]:
                increStack.append(i)
                i += 1
            else:
                tmp = height[increStack.pop()]
                area = max(area, tmp * ((i - increStack[-1] - 1) if (increStack) else i))
        return area

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django works (3): Testing Server and Static Files Serving