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.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
Example 1:
Input: [2,1,5,6,2,3]
Output: 10
Example 2:
Input: heights = [2,4]
Output: 4
Solution I: (Brute Force)
Algorithm:
Find the max area for a bar
Finding the leftmost valid limit
Finding the rightmost valid limit
Finding the area
classSolution{public:intlargestRectangleArea(vector<int> &heights) {int maxArea = INT_MIN;for (int i =0; i <heights.size(); i++) { //Finding left most limitint j, k;for (j = i; j >=0; j--) {if (heights[j] <heights[i]) {break; } } j++; //Finding right most limitfor (k = i; k <heights.size(); k++) {if (heights[k] <heights[i]) {break; } } k--;int area = (k - j +1) *heights[i];if (area > maxArea) { maxArea = area; } }return maxArea; }};