Created
October 25, 2019 16:46
-
-
Save vitkarpov/035e6c9e243ba822237a5d47827f7395 to your computer and use it in GitHub Desktop.
Largest Rectangle in Histogram (https://leetcode.com/problems/largest-rectangle-in-histogram)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Time: O(n * log (n)) | |
// Memory: O(log (n)) | |
/** | |
* @param {number[]} heights | |
* @return {number} | |
*/ | |
var largestRectangleArea = function(heights) { | |
if (!heights.length) { | |
return 0; | |
} | |
return maxArea(heights, 0, heights.length - 1); | |
}; | |
function maxArea(arr, left, right) { | |
if (left > right) { | |
return 0; | |
} | |
if (left === right) { | |
return arr[left]; | |
} | |
const min = indexOfMin(arr, left, right); | |
const leftMax = maxArea(arr, left, min - 1); | |
const rightMax = maxArea(arr, min + 1, right); | |
return Math.max(leftMax, rightMax, arr[min] * (right - left + 1)); | |
} | |
function indexOfMin(arr, left, right) { | |
let min = left; | |
for (let i = left + 1; i <= right; i++) { | |
if (arr[i] < arr[min]) { | |
min = i; | |
} | |
} | |
return min; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's not
O(n * log n)
, it'sn^2