Friday, 17 July 2015

ARRAYSUB

Standard

SUBARRAYS

Link to the question : ARRAYSUB 

HINT :

I have applied the basic approach and it got accepted.  First I started a loop from 0 to [size - k]. And then for sub sequence of k elements, I printed the maximum element. This is done by brute force.

RECOMMENDED QUESTION :

Try your hands on this mathematical question .

SOURCE CODE :

#include<iostream>

using namespace std;
int main()
{
    int n,k,i,j,m=0;
    cin>>n;
    int a[n];
    for(i=0;i<n;i++)
        cin>>a[i];
    cin>>k;
    for(i=0;i<=n-k;i++)
    {
        m=a[i];
        for(j=1;j<k;j++)
        {
            if(a[i+j]>m)
                m=a[i+j];
        }
        cout<<m<<" ";

    }
}

2 comments:

  1. #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    using namespace std;
    int main()
    {int t;
    cin>>t;
    int a[t];
    for(int i=1;i<=t;i++)
    {
    cin>>a[i];
    }
    int k;
    cin>>k;
    int u=k;
    int m=-1,v=1;
    for(int i=v;i<=k && i<=t;i++)
    {
    if(a[i]>m)
    m=a[i];

    if((i-(v-1))%u==0)
    {
    cout<<m<<" ";
    k+=1;

    i=v;
    v++;
    m=0;

    }




    }

    return 0;
    }
    why it shows time limit exceeded!!!

    ReplyDelete
    Replies
    1. Sorry for the late reply.
      Even I tried your code and it gives TLE. My algorithm has a time complexity of O(n*n) still it passes in 0.69s and your algo having a time complexity of of O(n) gives TLE.
      i think there must be some loop hole. Check for some trivial case, there might be an infinite loop running.

      Delete