In LeetCode problem #84, "Largest Rectangle in Histogram", we're given a bar graph in the form int[] heights
, and we need to find and return the area of the "largest rectangle" in the bar graph, meaning the maximum possible value of (j - i + 1) * min(heights[i], heights[i+1], ..., heights[j-1], heights[j])
(by choosing i
and j
appropriately).
Apparently the below solution gives average-case time complexity in O(n log n), worst-case time complexity in O(n2), and space complexity in O(n). Why is that? I'm particularly perplexed about how to think about it so that O(n log n) makes sense.
public class Solution {
public int calculateArea(int[] heights, int start, int end) {
if (start > end)
return 0;
int minindex = start;
for (int i = start; i <= end; i++) {
if (heights[minindex] > heights[i]) {
minindex = i;
}
}
return Math.max(
heights[minindex] * (end - start + 1),
Math.max(
calculateArea(heights, start, minindex - 1),
calculateArea(heights, minindex + 1, end)));
}
public int largestRectangleArea(int[] heights) {
return calculateArea(heights, 0, heights.length - 1);
}
}