Maximize the rectangular area under Histogram

前端 未结 11 867
天涯浪人
天涯浪人 2020-11-28 17:26

I have a histogram with integer heights and constant width 1. I want to maximize the rectangular area under a histogram. e.g.:

 _
| |
| |_ 
|   |
|   |_
|           


        
11条回答
  •  盖世英雄少女心
    2020-11-28 18:15

    You can use O(n) method which uses stack to calculate the maximum area under the histogram.

    long long histogramArea(vector &histo){
       stack s;
       long long maxArea=0;
       long long area= 0;
       int i =0;
       for (i = 0; i < histo.size();) {
        if(s.empty() || histo[s.top()] <= histo[i]){
            s.push(i++);
        }
        else{
            int top = s.top(); s.pop();
            area= histo[top]* (s.empty()?i:i-s.top()-1);
            if(area >maxArea)
                maxArea= area;
        }
      }
      while(!s.empty()){
        int top = s.top();s.pop();
        area= histo[top]* (s.empty()?i:i-s.top()-1);
        if(area >maxArea)
            maxArea= area;
     }
     return maxArea;
    }
    

    For explanation you can read here http://www.geeksforgeeks.org/largest-rectangle-under-histogram/

提交回复
热议问题