Histogram largest rectangle

Given n non-negative integer that represents the height of each column in the histogram. Each column adjacent to each other, and a width of 1.

In seeking this histogram, the maximum area can be outlined rectangle.

 

 

The above is an example of the histogram, wherein the width of each column is 1, given that the height of [2,1,5,6,2,3].

 

 

 

The shaded portion is the maximum that can be outlined by a rectangular area, an area of ​​10 units.

 

/**
 * @param {number[]} heights
 * @return {number}
 */
var largestRectangleArea = function(heights) {
//      let max = 0;

//     for(let j=heights.length-1;j>=0;j--){
//       for(let i=0;i<=j;i++){
//         let min = Math.min(...heights.slice(i,j+1));
//         if(max<(j-i+1)*min){
//           max = (j-i+1)*min;
//         }
//       }
//     }
//     return max;
    let max = 0;
    
    for(let i=0;i<heights.length;i++){

      let left_i= i;
      let right_i = i;

      while(left_i>=0&&heights[left_i]>=heights[i]) left_i--;
      left_i ++;
      while(right_i<heights.length&&heights[right_i]>=heights[i]) right_i++;
      right_i++;

      max = Math.max(max,(right_i-left_i-1)*heights[i]);

    }

    
    return max;
};

Implementation: The main area is to find the maximum value for each element, the method for finding the maximum area value: from the current position to find a left, a right found smaller than the current data element is less than the current data element, then the calculated maximum intermediate the area value.

Example:

Input: [2,1,5,6,2,3]
Output: 10

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/largest-rectangle-in-histogram
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/panjingshuang/p/11900432.html