#include
#include
using namespace std;
int max_left(int a[],int n,int k)
{
int max=-1;
for(int i=0;i<k;i++)
{
if(a[i]>max)
max=a[i];
}
return max;
}
int max_right(int a[],int n,int k)
{
int max=-1;
for(int i=k+1;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
return max;
}
int water_accumulated(int a[],int n)
{
int count=0;
for(int i=1;i<n-1;i++)
{
int r=max_right(a,n,i);
int l=max_left(a,n,i);
int ans=min(r,l)-a[i];
if(ans>0)
count+=ans;
}
return count;
}
int main()
{
int n;
cin>>n;
int* a=new int[n];
for(int i=0;i<n;i++)
cin>>a[i];
int ans=water_accumulated(a,n);
cout<<ans;
return 0;
}
Getting time limit exceeded for some test cases?
please send link of your code
it is difficult to find error of code here
you have to share the link
TLE will definetly comes as
time complexity is time complexity is O(n^3)
what you can do is make right max and left max array intially
and then use it in O(1)
so resultant time complexity wil be O(n)
this will pass all testcases