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 -
  1. Input values and find total sum of all terms
  2. Create a loop and calculate average term by term, use logic -> 
    1. sum= first element
    2. this_average=sum/elements in the sum
    3. SZ= Elements left in array= size-elements in sum
    4. other_average=(total-sum)/SZ
  3. Use if loop to find whether this_average is bigger than other_average or not.
  4. If true, input the (i+1)th and (j+1)th element in the pair, Increment counter by 1
  5. 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;
}








Popular posts from this blog

Missing Numbers (Hackerrank)

Find Missing Number (Amazon SDE)