• Friday, 17 February 2017

    Count Pairs in an Array -GeekforGeeks




    Question:

    Count Pairs in an Array -GeekforGeeks

    Link for question: GeeksforGeeks


    Input:

    2
    
    7
    
    5 0 10 2 4 1 6
    
    4
    
    8 4 2 1
    

    Output:

     5
     2 
    
    

    Explanation:

    • Run two loops
    • Run the outer loop from 0 to n-1 (0 to n-2 is enough).
    • Run the inner loop for i+1 to n-1 (Here n-1 is included).
    • Check the condition for each inner loop iteration and if it satisfies the conditon increase the counter.



    Code:

    #include<stdio.h>
    int func()
    {
      int n,i,j;
      //size of array
      scanf("%d",&n);
      int a[n];
      for(i=0;i<n;i++)
      {
        scanf("%d",&a[i]);
      }
      int count=0;
      //to count the no of pairs
      for(i=0;i<n;i++)
      {
        for(j=i+1;j<n;j++)
        {
          if(i*a[i] > j*a[j])
          {
            count++;
          //  printf("(%d,%d) ",i*a[i],j*a[j]);
          }
          
        }
      }
      //printf("\n");
      printf("%d\n",count);
      
    }
    int main()
    {
      int cases,z;
      scanf("%d",&cases);
      // no of test cases
      for(z=0;z<cases;z++)
      {
        func();
      }
      return 0;
    }
    




    If you like our blog.. Please share ....

    Thanks.... :)

    No comments:

    Post a Comment

    Follow Us on Facebook: