runnig

Max Histogram Area

Feb 4th, 2013
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. // Histogram
  2. class Solution {
  3. public:
  4.  
  5.     typedef vector<int> vec_t;    
  6.    
  7.     int largestRectangleArea(vec_t & histogram) {
  8.        
  9.         if(histogram.empty()) { return 0; }
  10.        
  11.         const size_t N = histogram.size();
  12.        
  13.         vec_t maxSoFarLeft(N);
  14.         vec_t maxSoFarRight(N);
  15.        
  16.         maxSoFarLeft[0] = histogram[0];
  17.         maxSoFarLeft[N-1] = histogram[N-1];
  18.        
  19.         for(size_t i = 1; i < N; ++i)
  20.         {          
  21.             int H = histogram[i];
  22.             size_t j = N-1-i;
  23.            
  24.             maxSoFarLeft[i] = max(histogram[i],maxSoFarLeft[i-1]);
  25.             maxSoFarLeft[i] = max(histogram[j],maxSoFarRight[j+1]);            
  26.         }
  27.        
  28.        
  29.         int maxArea = INT_MIN;
  30.        
  31.         for(size_t pos = 0; pos < N; ++pos)
  32.         {
  33.             const int H = histogram[pos];
  34.            
  35.            
  36.             typedef vec_t::iterator iter_t;
  37.            
  38.             iter_t begin_range = std::lower_bound(maxSoFarLeft.begin(), maxSoFarLeft.begin() + pos, H);
  39.             int beg_pos = std::distance(maxSoFarLeft.begin(), begin_range);
  40.            
  41.             iter_t end_range = std::upper_bound(maxSoFarRight.begin()+pos+1, maxSoFarRight.end(), H);
  42.             int end_pos = std::distance(maxSoFarRight.begin(), end_range);
  43.            
  44.             int area = H * (end_pos - beg_pos);
  45.             maxArea = std::max(maxArea, area);
  46.         }
  47.         return maxArea;
  48.     }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment