Skip to content

Instantly share code, notes, and snippets.

@markroxor
Created September 2, 2015 08:08
Show Gist options
  • Save markroxor/bda07e11e21b361fc497 to your computer and use it in GitHub Desktop.
Save markroxor/bda07e11e21b361fc497 to your computer and use it in GitHub Desktop.
SPOJ- Largest Histogram problem
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll maxHist(ll arr[],ll n)
{
stack<ll> st;
ll i=0,maxArea=0,tp;
while(i<n)
{
if(st.empty()||arr[i]>=arr[st.top()])
st.push(i++);
else
{
tp=st.top();
st.pop();
ll area=arr[tp]*(st.empty()?i:i-st.top()-1);
if(maxArea<area)
maxArea=area;
}
}
while(!st.empty())
{
tp=st.top();
st.pop();
ll area=arr[tp]*(st.empty()?i:i-st.top()-1);
if(maxArea<area)
maxArea=area;
}
return maxArea;
}
int main()
{
std::ios::sync_with_stdio(0);
while(true)
{
ll n;
cin>>n;
if(!n)
break;
ll arr[n+5];
for(ll i=0;i<n;i++)
cin>>arr[i];
cout<<maxHist(arr,n)<<"\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment