|
| 1 | +## Maximum Rectangular Area in a Histogram |
| 2 | +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, there will be N bars height of each bar will be given by the array arr. [🔗Goto](https://practice.geeksforgeeks.org/problems/maximum-rectangular-area-in-a-histogram-1587115620/1/?page=3&difficulty[]=1&status[]=unsolved&sortBy=submissions) |
| 3 | + |
| 4 | +<details> |
| 5 | +<summary>Full Code</summary> |
| 6 | + |
| 7 | +```java |
| 8 | +import java.util.*; |
| 9 | +import java.lang.*; |
| 10 | +import java.io.*; |
| 11 | + |
| 12 | +class GFG { |
| 13 | + |
| 14 | + |
| 15 | + public static void main (String[] args) throws IOException { |
| 16 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 17 | + int t = Integer.parseInt(br.readLine().trim()); |
| 18 | + while(t-->0){ |
| 19 | + long n = Long.parseLong(br.readLine().trim()); |
| 20 | + String inputLine[] = br.readLine().trim().split(" "); |
| 21 | + long[] arr = new long[(int)n]; |
| 22 | + for(int i=0; i<n; i++)arr[i]=Long.parseLong(inputLine[i]); |
| 23 | + System.out.println(new Solution().getMaxArea(arr, n)); |
| 24 | + } |
| 25 | + } |
| 26 | +} |
| 27 | +``` |
| 28 | +</details> |
| 29 | + |
| 30 | +```java |
| 31 | +class Solution |
| 32 | +{ |
| 33 | + //Function to find largest rectangular area possible in a given histogram. |
| 34 | + public static long getMaxArea(long hist[], long n) |
| 35 | + { |
| 36 | + long maxAns = 0; |
| 37 | + int ps[] = previousSmaller(hist); |
| 38 | + int ns[] = nextSmaller(hist); |
| 39 | + for(int i=0; i<hist.length; i++){ |
| 40 | + long cur = ((ns[i]-ps[i])-1)*hist[i]; |
| 41 | + maxAns = Math.max(cur,maxAns); |
| 42 | + } |
| 43 | + return maxAns; |
| 44 | + } |
| 45 | + public static int[] previousSmaller(long hist[]){ |
| 46 | + int[] ps = new int[hist.length]; |
| 47 | + Stack<Integer> s = new Stack<>(); |
| 48 | + for(int i=0; i<hist.length; i++){ |
| 49 | + while(!s.isEmpty() && hist[s.peek()] >= hist[i]){ |
| 50 | + s.pop(); |
| 51 | + } |
| 52 | + if(s.isEmpty()){ |
| 53 | + ps[i] = -1; |
| 54 | + }else{ |
| 55 | + ps[i] = s.peek(); |
| 56 | + } |
| 57 | + s.push(i); |
| 58 | + } |
| 59 | + return ps; |
| 60 | + } |
| 61 | + public static int[] nextSmaller(long hist[]){ |
| 62 | + int[] ns = new int[hist.length]; |
| 63 | + Stack<Integer> s = new Stack<>(); |
| 64 | + for(int i=hist.length-1; i>=0; i--){ |
| 65 | + while(!s.isEmpty() && hist[s.peek()] >= hist[i]){ |
| 66 | + s.pop(); |
| 67 | + } |
| 68 | + if(s.isEmpty()){ |
| 69 | + ns[i] = hist.length; |
| 70 | + }else{ |
| 71 | + ns[i] = s.peek(); |
| 72 | + } |
| 73 | + s.push(i); |
| 74 | + } |
| 75 | + return ns; |
| 76 | + } |
| 77 | +} |
| 78 | +``` |
0 commit comments