Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Largest Rectangle solution doesn't works #40

Open
javaHelper opened this issue Jul 7, 2021 · 1 comment
Open

Largest Rectangle solution doesn't works #40

javaHelper opened this issue Jul 7, 2021 · 1 comment

Comments

@javaHelper
Copy link

No description provided.

@javaHelper javaHelper changed the title Largest Reactangle solution doesn't works Largest Rectangle solution doesn't works Jul 7, 2021
@Jivan2020
Copy link

import java.util.Stack;

public class Main {
public static void main(String[] args) {
// Define the histogram
int[] histogram = {6, 2, 5, 4, 5, 1, 6};

// Find the area of the largest rectangle
int maxArea = findLargestRectangle(histogram);

// Print the result
System.out.println("Largest rectangle: " + maxArea);

}

public static int findLargestRectangle(int[] histogram) {
// Create a stack to store the indices of the histogram bars
Stack stack = new Stack<>();

// Initialize variables
int maxArea = 0;
int i = 0;

// Iterate through the histogram bars
while (i < histogram.length) {
  // If the stack is empty or the current bar is taller than the one on top of the stack, push the current bar's index onto the stack
  if (stack.isEmpty() || histogram[i] >= histogram[stack.peek()]) {
    stack.push(i++);
  } else {
    // Otherwise, calculate the area of the rectangle using the bar on top of the stack as the height
    int height = histogram[stack.pop()];
    int width = stack.isEmpty() ? i : i - stack.peek() - 1;
    int area = height * width;

    // Update the maximum area if necessary
    maxArea = Math.max(maxArea, area);
  }
}

// Calculate the remaining rectangles in the stack
while (!stack.isEmpty()) {
  int height = histogram[stack.pop()];
  int width = stack.isEmpty() ? i : i - stack.peek() - 1;
  int area = height * width;
  maxArea = Math.max(maxArea, area);
}

return maxArea;

}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants