refactor: clean up LargestRectangle and convert tests to parameterized format (#6356)

* refactor: clean up LargestRectangle and convert tests to parameterized format

* refactor: fix clang formatting issue

* refactor: fix clang formatting issue for test data

---------

Co-authored-by: Deniz Altunkapan <93663085+DenizAltunkapan@users.noreply.github.com>
This commit is contained in:
Oleksandr Klymenko
2025-07-11 22:32:42 +03:00
committed by GitHub
parent f3252793e1
commit 2ccc15671f
2 changed files with 47 additions and 82 deletions

View File

@@ -3,36 +3,50 @@ package com.thealgorithms.stacks;
import java.util.Stack;
/**
* Utility class to calculate the largest rectangle area in a histogram.
* Each bar's width is assumed to be 1 unit.
*
* @author mohd rameez github.com/rameez471
* <p>This implementation uses a monotonic stack to efficiently calculate
* the area of the largest rectangle that can be formed from the histogram bars.</p>
*
* <p>Example usage:
* <pre>{@code
* int[] heights = {2, 1, 5, 6, 2, 3};
* String area = LargestRectangle.largestRectangleHistogram(heights);
* // area is "10"
* }</pre>
*/
public final class LargestRectangle {
private LargestRectangle() {
}
/**
* Calculates the largest rectangle area in the given histogram.
*
* @param heights an array of non-negative integers representing bar heights
* @return the largest rectangle area as a {@link String}
*/
public static String largestRectangleHistogram(int[] heights) {
int n = heights.length;
int maxArea = 0;
Stack<int[]> st = new Stack<>();
for (int i = 0; i < n; i++) {
Stack<int[]> stack = new Stack<>();
for (int i = 0; i < heights.length; i++) {
int start = i;
while (!st.isEmpty() && st.peek()[1] > heights[i]) {
int[] tmp = st.pop();
maxArea = Math.max(maxArea, tmp[1] * (i - tmp[0]));
start = tmp[0];
while (!stack.isEmpty() && stack.peek()[1] > heights[i]) {
int[] popped = stack.pop();
maxArea = Math.max(maxArea, popped[1] * (i - popped[0]));
start = popped[0];
}
st.push(new int[] {start, heights[i]});
stack.push(new int[] {start, heights[i]});
}
while (!st.isEmpty()) {
int[] tmp = st.pop();
maxArea = Math.max(maxArea, tmp[1] * (n - tmp[0]));
int totalLength = heights.length;
while (!stack.isEmpty()) {
int[] remaining = stack.pop();
maxArea = Math.max(maxArea, remaining[1] * (totalLength - remaining[0]));
}
return Integer.toString(maxArea);
}
public static void main(String[] args) {
assert largestRectangleHistogram(new int[] {2, 1, 5, 6, 2, 3}).equals("10");
assert largestRectangleHistogram(new int[] {2, 4}).equals("4");
}
}