Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. // C++ program to find maximum rectangular area in
  2. // linear time
  3. #include<iostream>
  4. #include<stack>
  5.  
  6. using namespace std;
  7.  
  8.  
  9. // The main function to find the maximum rectangular
  10. // area under given histogram with n bars
  11.  
  12. int getMaxArea(int hist[], int n)
  13. {
  14.  
  15. // Create an empty stack. The stack holds indexes
  16.  
  17. // of hist[] array. The bars stored in stack are
  18.  
  19. // always in increasing order of their heights.
  20.  
  21. stack<int> s;
  22.  
  23.  
  24.  
  25. int max_area = 0; // Initialize max area
  26.  
  27. int tp; // To store top of stack
  28.  
  29. int area_with_top; // To store area with top bar
  30.  
  31. // as the smallest bar
  32.  
  33.  
  34.  
  35. // Run through all bars of given histogram
  36.  
  37. int i = 0;
  38.  
  39. while (i < n)
  40.  
  41. {
  42.  
  43. // If this bar is higher than the bar on top
  44.  
  45. // stack, push it to stack
  46.  
  47. if (s.empty() || hist[s.top()] <= hist[i])
  48.  
  49. s.push(i++);
  50.  
  51.  
  52.  
  53. // If this bar is lower than top of stack,
  54.  
  55. // then calculate area of rectangle with stack
  56.  
  57. // top as the smallest (or minimum height) bar.
  58.  
  59. // 'i' is 'right index' for the top and element
  60.  
  61. // before top in stack is 'left index'
  62.  
  63. else
  64.  
  65. {
  66.  
  67. tp = s.top(); // store the top index
  68.  
  69. s.pop(); // pop the top
  70.  
  71.  
  72.  
  73. // Calculate the area with hist[tp] stack
  74.  
  75. // as smallest bar
  76.  
  77. area_with_top = hist[tp] * (s.empty() ? i :
  78.  
  79. i - s.top() - 1);
  80.  
  81.  
  82.  
  83. // update max area, if needed
  84.  
  85. if (max_area < area_with_top)
  86.  
  87. max_area = area_with_top;
  88.  
  89. }
  90.  
  91. }
  92.  
  93.  
  94.  
  95. // Now pop the remaining bars from stack and calculate
  96.  
  97. // area with every popped bar as the smallest bar
  98.  
  99. while (s.empty() == false)
  100.  
  101. {
  102.  
  103. tp = s.top();
  104.  
  105. s.pop();
  106.  
  107. area_with_top = hist[tp] * (s.empty() ? i :
  108.  
  109. i - s.top() - 1);
  110.  
  111.  
  112.  
  113. if (max_area < area_with_top)
  114.  
  115. max_area = area_with_top;
  116.  
  117. }
  118.  
  119.  
  120.  
  121. return max_area;
  122. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement