tygarian

largest rectangle area in histogram optimized code leetcode

Jan 29th, 2022
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. class Solution {
  2. public:
  3. // Time Complexity:- O(N)
  4. // Space Complexity:- O(N)
  5. int largestRectangleArea(vector<int>& heights) {
  6. int n = heights.size();
  7. stack <int> index; // stack helps in storing increasing elements indices
  8.  
  9. int max_area = 0;
  10. for(int i=0;i<heights.size();i++){
  11. while(!index.empty() and heights[i]<heights[index.top()]){
  12. int w = heights[index.top()];
  13. index.pop();
  14.  
  15. int left = index.empty()?-1:index.top();
  16. int right = i;
  17.  
  18. int l = right - left - 1;
  19.  
  20. max_area = max(max_area,l*w);
  21. }
  22. index.push(i);
  23. }
  24.  
  25. while(!index.empty()){
  26. int w = heights[index.top()];
  27. index.pop();
  28.  
  29. int left = index.empty()?-1:index.top();
  30. int right = n;
  31.  
  32. int l = right - left - 1;
  33.  
  34. max_area = max(max_area,l*w);
  35. }
  36.  
  37. return max_area;
  38. }
  39. };
Add Comment
Please, Sign In to add comment