Finding the Subarrays (Hackerearth)
Finding subarrays can become a cumbersome task to handle if we don't know the right approach for it. In this particular question we will be using a new method.
Pair is used to combine together two values which may be different in type. Pair provides a way to store two heterogeneous objects as a single unit. Such as vector<first attribute, second attribute>.
To access these attributes we use keywords 'first' and 'second'
Approach -
- Input values and find total sum of all terms
- Create a loop and calculate average term by term, use logic ->
- sum= first element
- this_average=sum/elements in the sum
- SZ= Elements left in array= size-elements in sum
- other_average=(total-sum)/SZ
- Use if loop to find whether this_average is bigger than other_average or not.
- If true, input the (i+1)th and (j+1)th element in the pair, Increment counter by 1
- Sort the pair and output it.
Code-
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n ,count =0;
cin>>n;
int arr[n];
double total;
for(int i= 0; i<n ;i++)
{
cin>>arr[i];
total+=arr[i];
}
vector<pair<int,int>> v; //vector of pairs
double sum, this_average, other_average;
for(int i=0;i<n;i++)
{
sum=0;
for(int j=i;j<n;j++)
{
sum+=arr[j];
this_average=sum/(j-i+1);
int sz= n-j+i-1;
other_average=(sz>0)?(total-sum)/sz:0;
if(this_average>other_average)
{
v.push_back({i+1,j+1});
count++;
}
}
}
cout<<count<<endl;
sort(v.begin(), v.end());
for(int i=0;i<v.size(); i++)
{
cout<<v[i].first<<" "<<v[i].second<<endl;
}
return 0;
return 0;
}