Skip to content

Instantly share code, notes, and snippets.

@ajinkyajawale14499
Created June 29, 2019 18:47
Show Gist options
  • Save ajinkyajawale14499/567aa0823ddad23ba0ca7ac08ccaa836 to your computer and use it in GitHub Desktop.
Save ajinkyajawale14499/567aa0823ddad23ba0ca7ac08ccaa836 to your computer and use it in GitHub Desktop.
Largest Histogram using dynamic programming
public static int largestRectangleArea(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
int[] lessFromLeft = new int[height.length]; // idx of the first bar the left that is lower than current
int[] lessFromRight = new int[height.length]; // idx of the first bar the right that is lower than current
lessFromRight[height.length - 1] = height.length;
lessFromLeft[0] = -1;
for (int i = 1; i < height.length; i++) {
int p = i - 1;
while (p >= 0 && height[p] >= height[i]) {
p = lessFromLeft[p];
}
lessFromLeft[i] = p;
}
for (int i = height.length - 2; i >= 0; i--) {
int p = i + 1;
while (p < height.length && height[p] >= height[i]) {
p = lessFromRight[p];
}
lessFromRight[i] = p;
}
int maxArea = 0;
for (int i = 0; i < height.length; i++) {
maxArea = Math.max(maxArea, height[i] * (lessFromRight[i] - lessFromLeft[i] - 1));
}
return maxArea;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment