Skip to content

Instantly share code, notes, and snippets.

@vijaytv
Last active March 18, 2017 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vijaytv/b8d132be01ecb29c4929a0ec78d4fa02 to your computer and use it in GitHub Desktop.
Save vijaytv/b8d132be01ecb29c4929a0ec78d4fa02 to your computer and use it in GitHub Desktop.
Find largest rectangle in Histigram
//Find the largest rectangle in a histogram.
var myList = [1,3,4,24,26,3,0,2,2,0,2,2,0,2,2,2,0,2,2,2];
function getLargestRect(arr) {
var result = arr.reduce(function(obj,item) {
if (item < 1) {
obj.runningItems = [];
return obj;
}
obj.runningItems = obj.runningItems || [];
obj.runningItems.push(item);
obj.runningItems.forEach(function(el,idx){
var tmpArray = obj.runningItems.slice(idx);
var result = Math.min.apply(null, tmpArray) * tmpArray.length ;
obj.maxArea = result > obj.maxArea ? result : obj.maxArea;
});
return obj;
},{maxArea:0});
return result.maxArea;
}
var result = getLargestRect(myList);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment