https://mycode.prepbytes.com/problems/arrays/WLTYFAT
My approach :-
- find all the possible segment of length L
- find all the possible segment of length R
- then find if a particular segment of L and Segment of R is valid
- if valid and then sum is greater than max than store it to max
My code
#include <bits/stdc++.h>
using namespace std;
class storage
{ public:
pair<int,int>p;
int sum;
};
int isValid(pair<int,int>p1,pair<int,int>p2)
{
int i1=p1.first, i2=p2.first;
int j1=p1.second, j2=p2.second;
//cout<<"i1 j1 are "<<i1<<" "<<j1<<endl;
//cout<<"i2 j2 are "<<i2<<" "<<j2<<endl;
if(((i1>=i2)&&(i1<=j2))||((j1>=i2)&&(j1<=j2)))
{
return 0;
}
return 1;
}
vector<storage> slidingWindow(int *arr,int n,int w)
{
vector<storage> v;
int l=w;
int z=0,size=0;int start=0;
int val=0;
while(z<n)
{
val+=arr[z];
size++;
if(size==l)
{
storage s;
s.sum=val;
s.p.first=start;
s.p.second=z;
val-=arr[start];
start++;
size--;
v.push_back(s);
}
z++;
}
return v;
}
int main()
{
int t ; cin>>t ;
for(int i=0;i<t;i++)
{
int n ; cin>>n;
int arr[n];
for(int j=0;j<n;j++)
{
cin>>arr[j];
}
int l,r; cin>>l>>r;
vector<storage> left = slidingWindow(arr,n,l);
vector<storage> right= slidingWindow(arr,n,r);
/* for(int g=0;g<right.size();g++)
{
cout<<"first and last indices are "<<right[g].p.first<<" "<<right[g].p.second<<endl;
cout<<"val is "<<right[g].sum<<endl;
cout<<endl;
}
*/
int max=0;
for(int g=0;g<left.size();g++)
{
for(int gg=0;gg<right.size();gg++)
{
int val=isValid(left[g].p,right[gg].p);
if(val==1)
{
if((left[g].sum+right[gg].sum)>max)
max=(left[g].sum+right[gg].sum);
}
}
}
cout<<max<<endl;
}
}