Advertisement
Guest User

Untitled

a guest
Jan 20th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int largestRectangleArea(vector<int>& heights) {
  4.         vector<int> nearest_smaller_left(heights.size()); // indices
  5.         auto nearest_smaller_right = nearest_smaller_left;
  6.        
  7.         stack<int> min_stack;
  8.         for (int i = 0; i < heights.size(); ++i) {
  9.             while(!min_stack.empty() && heights[min_stack.top()] >= heights[i])
  10.                 min_stack.pop();
  11.            
  12.             nearest_smaller_left[i] = min_stack.empty() ? -1 : min_stack.top();
  13.             min_stack.push(i);
  14.         }
  15.         min_stack = {};
  16.         for (int i = heights.size() - 1; i >= 0; --i) {
  17.             while(!min_stack.empty() && heights[min_stack.top()] >= heights[i])
  18.                 min_stack.pop();
  19.            
  20.             nearest_smaller_right[i] = min_stack.empty() ? heights.size() : min_stack.top();
  21.             min_stack.push(i);
  22.         }
  23.        
  24.         int max_area = 0;
  25.         for (int i = 0; i < heights.size(); ++i) {
  26.             int width = nearest_smaller_right[i] - nearest_smaller_left[i] - 1;
  27.             max_area = max(max_area, heights[i] * width);
  28.         }
  29.        
  30.         return max_area;
  31.     }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement