Created
March 6, 2019 20:44
-
-
Save daftAnorak/529dbfc75f0cae9ce46d1e0e2dcaf207 to your computer and use it in GitHub Desktop.
Function which calculates the largest area from a range of histogram points
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
/** | |
* Largest Rectangle from Histogram | |
* | |
* function which takes a range of histogram points, | |
* (array of natural numbers [or zero]), and returns the | |
* largest rectangle area that can fit inside of it. | |
* | |
* @param {Array<Number>} points The range of histogram points | |
* @return {Number} The largest rectangle area | |
* | |
* @example | |
* | |
* largestRectangleArea([3,1,4,2,5]); // => 6 | |
* largestRectangleArea([2,3,4,1,7]); // => 7 | |
* largestRectangleArea([7,0,5,4,5,4,0,11,12,8]); // => 24 | |
* largestRectangleArea([]); // => 0 | |
* | |
*/ | |
function largestRectangleArea(points) { | |
return points.reduce( | |
(currentSums, point) => { | |
let len = point + 1; | |
let nextSums = new Array(len); | |
while (len--) { | |
nextSums[len] = (currentSums[len] || 0) + len; | |
} | |
nextSums[0] = Math.max(...nextSums); | |
return nextSums; | |
}, | |
[0] | |
)[0]; | |
} | |
export default largestRectangleArea; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment