Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions Largest_Histogram.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import java.util.Stack;

public class Histogram {

public int largestRectangleArea(int[] heights) {
// If the histogram is empty, return 0
if (heights == null || heights.length == 0) {
return 0;
}

int maxArea = 0;
Stack<Integer> stack = new Stack<>();

for (int i = 0; i < heights.length; i++) {
// While the current bar is shorter than the bar at the top of the stack
while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) {
int height = heights[stack.pop()]; // Height of the bar
// Width of the rectangle. If stack is empty, use current index, otherwise, difference of indices
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
maxArea = Math.max(maxArea, height * width);
}
stack.push(i); // Push current bar's index to the stack
}

// Calculate remaining areas for the bars in the stack
while (!stack.isEmpty()) {
int height = heights[stack.pop()];
int width = stack.isEmpty() ? heights.length : heights.length - stack.peek() - 1;
maxArea = Math.max(maxArea, height * width);
}

return maxArea;
}

public static void main(String[] args) {
Histogram histogram = new Histogram();
int[] heights = {2, 1, 5, 6, 2, 3};
System.out.println(histogram.largestRectangleArea(heights)); // Expected output: 10
}
}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ SR No | Program | Author
22 | Prime Number program | [Moola Pravalesh](https://github.com/MoolaPravalesh19)
23 | Caesar Cipher Program | [Ankush Dutta](https://github.com/GenDelta)
24 | Kadane's Algorithm | [Deepak Maurya](https://github.com/deepakmaur)

25 | Largest Histogram Sliding Window | [Shivansh Singh](https://github.com/shivanshsin0203)