Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Tuesday, April 4, 2017

Maximum Rectangular Area in a Histogram Java solution


Explanation :


Here we will push element into stack until the value of array at the position top of the stack is less than the coming value.
If not then pop values until he value of array at the position top of the stack is less than the coming value and calculate area upon the poped value. check if it is greater than max area if so then change max area.
and at last check the value in stack and calculate are upon them



import java.util.*;
import java.lang.*;
import java.io.*;
class hackerranksolutionc
 {
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t>0)
{
   int n=ab.nextInt();
   int arr[]=new int[n];
   int area,max_area=0;
   for(int i=0;i<n;i++)
   arr[i]=ab.nextInt();
   int i=0,top;
   Stack<Integer> stack =new Stack<Integer>();
   while(i<n)
   {
       if(stack.empty()|| arr[stack.peek()]<=arr[i])
       stack.push(i++);
       else
       {
           top=stack.pop();
           area=arr[top] * (stack.empty() ? i : i - stack.peek() - 1);
         
       if(area>max_area)
       max_area=area;
       }
   }
   while(!stack.empty())
   {
       top=stack.pop();
           area=arr[top] * (stack.empty() ? i : i - stack.peek() - 1);
         
       if(area>max_area)
       max_area=area;
   }
   System.out.println(max_area);
   t--;
}
}
}



0 Comments:

Post a Comment

Stats