|
| 1 | +/* |
| 2 | +Maximum Rectangular Area in a Histogram |
| 3 | +========================================== |
| 4 | +
|
| 5 | +Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have the same width and the width is 1 unit. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +Input: |
| 9 | +N = 7 |
| 10 | +arr[] = {6,2,5,4,5,1,6} |
| 11 | +Output: 12 |
| 12 | +Explanation: |
| 13 | +
|
| 14 | +Example 2: |
| 15 | +Input: |
| 16 | +N = 8 |
| 17 | +arr[] = {7 2 8 9 1 3 6 5} |
| 18 | +Output: 16 |
| 19 | +Explanation: Maximum size of the histogram |
| 20 | +will be 8 and there will be 2 consecutive |
| 21 | +histogram. And hence the area of the |
| 22 | +histogram will be 8x2 = 16. |
| 23 | +Your Task: |
| 24 | +The task is to complete the function getMaxArea() which takes the array arr[] and its size N as inputs and finds the largest rectangular area possible and returns the answer. |
| 25 | +
|
| 26 | +Expected Time Complxity : O(N) |
| 27 | +Expected Auxilliary Space : O(N) |
| 28 | +
|
| 29 | +Constraints: |
| 30 | +1 ≤ N ≤ 106 |
| 31 | +1 ≤ arr[i] ≤ 1012 |
| 32 | +*/ |
| 33 | + |
| 34 | +long long getMaxArea(long long arr[], int n) |
| 35 | +{ |
| 36 | + stack<int> st; |
| 37 | + vector<int> left(n, -1), right(n, n); |
| 38 | + for (int i = 0; i < n; ++i) |
| 39 | + { |
| 40 | + while (st.size() && arr[st.top()] >= arr[i]) |
| 41 | + st.pop(); |
| 42 | + left[i] = (st.size() ? st.top() : -1); |
| 43 | + st.push(i); |
| 44 | + } |
| 45 | + |
| 46 | + while (st.size()) |
| 47 | + st.pop(); |
| 48 | + |
| 49 | + for (int i = n - 1; i >= 0; --i) |
| 50 | + { |
| 51 | + while (st.size() && arr[st.top()] >= arr[i]) |
| 52 | + st.pop(); |
| 53 | + right[i] = (st.size() ? st.top() : n); |
| 54 | + st.push(i); |
| 55 | + } |
| 56 | + |
| 57 | + long long ans = 0; |
| 58 | + for (int i = 0; i < n; ++i) |
| 59 | + { |
| 60 | + long long width = right[i] - left[i] - 1; |
| 61 | + ans = max(ans, arr[i] * width); |
| 62 | + } |
| 63 | + |
| 64 | + return ans; |
| 65 | +} |
0 commit comments