Java-aid / Hackerrank-Solutions

hackerrank solutions github | hackerrank all solutions | hackerrank solutions for java | hackerrank video tutorial | hackerrank cracking the coding interview solutions | hackerrank data structures | hackerrank solutions algorithms | hackerrank challenge | hackerrank coding challenge | hackerrank algorithms solutions github| hackerrank problem solving | hackerrank programs solutions | JAVAAID |all hackerrank solutions | Coding Interview Preparation
https://www.youtube.com/c/JavaAidTutorials?sub_confirmation=1
MIT License
1.73k stars 862 forks source link

Largest Rectangle solution doesn't works #40

Open javaHelper opened 3 years ago

Jivan2020 commented 1 year ago

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;

} }