Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to efficiently find the area of largest rectangle that can be formed by adjacent buildings with known heights, in Java?

/*
	This is an implementation that demonstrates
	how to efficiently find the area of largest 
	rectangle that can be formed from a number
	of adjacent buildings, whose heights are given
	in an array of integers.

	Let n be the number of buildings.

	Time complexity: O(n) 
	Space complexity: O(n)
*/
import java.util.Stack;
import java.util.ArrayList;
import java.util.Arrays;

public class LargestRectangleArea {
	public static void main(String[] args) {
		Integer[] heights = { 1, 3, 3, 2, 4, 1, 5, 3, 2 };
		ArrayList<Integer> buildings = new ArrayList<Integer>(Arrays.asList(heights));
		System.out.println(largestRectangleUnderSkyline(buildings)); // 9
	}

	private static int largestRectangleUnderSkyline(ArrayList<Integer> buildings) {
		Stack<Integer> stack = new Stack<>();
		int[] maxArea = new int[1];
		int currentBuildingIdx;
		for (currentBuildingIdx = 0; currentBuildingIdx < buildings.size();) {
			if (stack.isEmpty() || buildings.get(stack.peek()) <= buildings.get(currentBuildingIdx)) {
				stack.push(currentBuildingIdx++);
			} else {
				updateMaxArea(stack, buildings, maxArea, currentBuildingIdx);
			}
		}

		while (!stack.isEmpty()) {
			updateMaxArea(stack, buildings, maxArea, currentBuildingIdx);
		}

		return maxArea[0];
	}

	private static void updateMaxArea(Stack<Integer> stack, ArrayList<Integer> buildings, int[] maxArea,
			int currentBuildingIdx) {
		int currentArea;
		int topBuildingIdx = stack.pop();
		if (stack.isEmpty()) {
			currentArea = buildings.get(topBuildingIdx) * currentBuildingIdx;
		} else {
			currentArea = buildings.get(topBuildingIdx) * (currentBuildingIdx - 1 - stack.peek());
		}
		if (currentArea > maxArea[0]) {
			maxArea[0] = currentArea;
		}
	}

}
Comment

PREVIOUS NEXT
Code Example
Java :: Java char data type 
Java :: sc.nextline skips 
Java :: java array print 
Java :: how to save a string to a text file 
Java :: java what is at 
Java :: flink prometheus alert on failed jobs 
Java :: hexstring to string In java 
Java :: how to add a list in a list java 
Java :: java fot 
Java :: java vector push_back 
Java :: maven artifact 
Java :: set spring context 
Java :: pre increment and post increments 
Java :: check if first character of a string is a number java 
Java :: send message bukkit 
Java :: java time 
Java :: advantages of exception handling in java 
Java :: imageview.setbackground 
Java :: loop through number java 
Java :: java 2 decimals 
Java :: Date(Long) to integer and back 
Java :: java long 
Java :: import android.support.v7.app.alertdialog androidx 
Java :: from file to array java 
Java :: équivalent setTimeInterval java 
Java :: html alert box android 
Java :: java 8 stream option 
Java :: boolean in java 
Java :: lauch java batch 
Java :: java remove item from list 
ADD CONTENT
Topic
Content
Source link
Name
5+2 =