-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumHistogram.cpp
More file actions
85 lines (79 loc) · 1.88 KB
/
Copy pathMaximumHistogram.cpp
File metadata and controls
85 lines (79 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
ALGORITHM:
1.Add to a stack(i.e the indices) if current value is equal or bigger than the top of the stack.
2.Otherwise keep removing from the stack till a number which is smaller or empty//equal than current is found.
3.Calculate Area every time you remove as
if(stack is empty)
area=input[top]*i;
else
area=input[top]*(i-stacktop-1)
Ref:
*/
#include<iostream>
#include<stack>
using namespace std;
/*
int main()
{
stack<int> s;
int arr[3]={1,2,4};
int i=0,area,max_area=-1;
int len=sizeof(arr)/sizeof(int);
//cout<<len;
s.push(i);
int top=s.top();
if(arr[i]>=arr[top])
{
s.push(++i);
top=s.top();
}else{
top=s.top();
s.pop();
i++;
if(s.empty())
{
area=arr[top]*i;
}
else{
area=arr[top]*(i-top-1);
}
if (max_area<area)
max_area=area;
}
cout<<max_area;
return 0;
}
*/
int main()
{
//In this case what we do is to find the minimum bar height and multiply with the span to get the area.
//int arr[3]={1,2,4};
//int arr[7]={6,2,5,4,5,1,6}; //Ans=3*4=12
int arr[4]={1,1,4,4};
int i,j,area=0,max_area=0,smallest_ht=0;
int len=sizeof(arr)/sizeof(int);
for(i=0;i<len;i++)
{
//small_ht=arr[i];
smallest_ht=arr[i];
for(j=i;j<len;j++)
{
//smallest_ht=arr[i];
if(smallest_ht>arr[j])
{
smallest_ht=arr[j];
//area=arr[i]*(j+1);
//cout<<arr[j]<<" ";
//}else{
//area=arr[j]*(j+1);
//smallest_ht=arr[j];
}
//cout<<smallest_ht<<" ";
area=smallest_ht*(j-i+1);
//cout<<area<<endl;
if(max_area<area)
max_area=area;
}
}
cout<<"Max Area=> "<<max_area;
}