Largest Rectangle


Problem Statement :


Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed.

There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join  adjacent buildings, they will form a solid rectangle of area .

For example, the heights array . A rectangle of height  and length  can be constructed within the boundaries. The area formed is .

Function Description

Complete the function largestRectangle int the editor below. It should return an integer representing the largest rectangle that can be formed within the bounds of consecutive buildings.

largestRectangle has the following parameter(s):

h: an array of integers representing building heights
Input Format

The first line contains n,  the number of buildings.
The second line contains n space-separated integers, each representing the height of a building.

Output Format

Print a long integer representing the maximum area of rectangle formed.



Solution :



title-img


                            Solution in C :

In C ++ :




#include <stack>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int N, h[100005];
int p = 1, s[100005];
int main() {
    scanf("%d", &N);
    for (int i = 1; i <= N; ++i) scanf("%d", &h[i]);
    int ans = 0;
    for (int i = 0; i < N + 2; ++i) {
        while (h[i] < h[s[p - 1]]) {
            int y = h[s[p - 1]];
            p--;
            ans = max(ans, (i - s[p - 1] - 1) * y);
        }
        s[p++] = i;
    }
    printf("%d\n", ans);
    return 0;
}








In Java :






import java.io.*;
import java.util.*;

public class Solution {
	static boolean[] valid;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		long[] ar = new long[n];


		for(int i=0; i<n; i++)
			ar[i] = sc.nextInt();
		
		int[] left = new int[n];
		int[] right = new int[n];
		Arrays.fill(left, -1); Arrays.fill(right, -1);

		Stack<Integer> st = new Stack<Integer>();

		for(int i=0; i<n; i++){
			while(st.size() > 0){
				if(ar[st.peek()] < ar[i]){
					left[i] = st.peek();
					break;
				}
				else
					st.pop();
			}
			st.push(i);
		}
		st.clear();
		for(int i=n-1; i>=0; i--){
			while(st.size() > 0){
				if(ar[st.peek()] < ar[i]){
					right[i] = st.peek();
					break;
				}
				else
					st.pop();
			}
			st.push(i);
		}
		// pArray(left);
		// pArray(right);
		long max = Integer.MIN_VALUE;
		for(int i=0; i<n; i++){
			long ans = 0;
			if(left[i] >= 0)
				ans+=ar[i]*(i - left[i] -1);
            else
                ans += ar[i] * i;
			if(right[i] > -1)
				ans+=ar[i]*(right[i] - i -1);
			else
				ans += ar[i] * (n - i-1);
			ans += ar[i];
			if(ans > max)
				max = ans;
			//System.out.println(ans);
		}
		System.out.println(max);
	}

	static void pArray(int[] ar){
		for(int i=0; i<ar.length; i++)
			System.out.print(ar[i] + " ");
		System.out.println();

	}
}








In  C :





#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
    
    int i, j, k, n, h;
    int ar[100000];
    int area, max=0;
    
    scanf("%d",&n);
    for(i=0;i<=n;++i)
        scanf("%d",&ar[i]);
    
    for(i=0;i<=n;++i)
        {
        int c = 1;
        j = i-1;
        k = i+1;
        
        while(j>=0 && ar[j]>ar[i]){
            j--;
            c++;
        }
        while(k<=n && ar[k]>ar[i]){
            k++;
            c++;
        }
        
        
        area = c * ar[i];
        
        max = (area>max)? area : max;
       
    }
    
    printf("%d",max);
    return 0;
}








In  Python3 :






def solve(H) :
    s,i,m = [],0,0
    while i < len(H) :
        if not s or H[i] > H[s[-1]] :
            s.append(i)
            i += 1
        else :
            t = s.pop()
            a = H[t] * ((i - s[-1] -1)  if s else i)
            if a > m :
                m = a
                
    while s :
        t = s.pop()
        a = H[t] * ((i - s[-1] -1)  if s else i)
        if a > m :
            m = a
        
    return m           

N = int(input())
H = list(int(_) for _ in input().split())

print(solve(H))
                        








View More Similar Problems

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →