Count pairs in an array that hold i*arr[i] > j*arr[j]

Given an array of integers arr[0..n-1], count all pairs (arr[i], arr[j]) in the such that i*arr[i] > j*arr[j], 0 =< i < j < n.

Examples :

Input : arr[] = {5 , 0, 10, 2, 4, 1, 6}
Output: 5
 Pairs which hold condition i*arr[i] > j*arr[j]
 are (10, 2) (10, 4) (10, 1) (2, 1) (4, 1)

Input  : arr[] = {8, 4, 2, 1}
Output : 2

A Simple solution is to run two loops. Pick each element of array one-by-one and for each element find element on right side of array that hold condition, then increment counter and last return counter value.
Below is the implementation of above idea:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to count all pair that
// hold condition i*arr[i] > j*arr[j]
#include<iostream>
using namespace std;
  
// Return count of pair in given array
// such that  i*arr[i] > j*arr[j]
int CountPair(int arr[] , int n )
{
    int result = 0; // Initialize result
  
    for (int i=0; i<n; i++)
    {
        // Generate all pair and increment
        // counter if the hold given condition
        for (int j = i + 1; j < n; j++)
            if (i*arr[i] > j*arr[j] )
                result ++;
    }
    return result;
}
  
// Driver code
int main()
{
    int arr[] = {5 , 0, 10, 2, 4, 1, 6} ;
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << "Count of Pairs : "
         << CountPair(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code for Count pairs in an
// array that hold i*arr[i] > j*arr[j]
class GFG {
      
    // Return count of pair in given array
    // such that  i*arr[i] > j*arr[j]
    public static int CountPair(int arr[] , int n )
    {
        int result = 0; // Initialize result
       
        for (int i = 0; i < n; i++)
        {
            // Generate all pair and increment
            // counter if the hold given condition
            for (int j = i + 1; j < n; j++)
                if (i*arr[i] > j*arr[j] )
                    result ++;
        }
        return result;
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int arr[] = {5 , 0, 10, 2, 4, 1, 6} ;
        int n = arr.length;
        System.out.println("Count of Pairs : " +
                            CountPair(arr, n));
    }
  }
// This code is contributed by Arnav Kr. Mandal.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# C# Code to Count pairs in an
# array that hold i*arr[i] > j*arr[j]
  
# Return count of pair in given array
# such that i*arr[i] > j*arr[j]
def CountPair(arr , n ):
      
    # Initialize result
    result = 0;
      
    for i in range (0, n):
          
        # Generate all pair and increment
        # counter if the hold given condition
        j = i + 1
        while(j < n):
            if (i * arr[i] > j * arr[j] ):
                result = result +1
            j = j + 1
    return result;
      
# Driver program to test above function */
      
arr = [5, 0, 10, 2, 4, 1, 6]
n = len(arr)
print("Count of Pairs : " , CountPair(arr, n))
  
# This code is contributed by Sam007.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Code to Count pairs in an
// array that hold i*arr[i] > j*arr[j]
using System;
  
class GFG
{
    // Return count of pair in given array
    // such that i*arr[i] > j*arr[j]
    public static int CountPair(int []arr , int n )
    {
        // Initialize result
        int result = 0;
      
        for (int i = 0; i < n; i++)
        {
            // Generate all pair and increment
            // counter if the hold given condition
            for (int j = i + 1; j < n; j++)
                if (i*arr[i] > j*arr[j] )
                    result ++;
        }
        return result;
    }
      
    /* Driver program to test above function */
    public static void Main() 
    {
        int []arr = {5, 0, 10, 2, 4, 1, 6};
        int n = arr.Length;
        Console.WriteLine("Count of Pairs : " +
                           CountPair(arr, n));
    }
}
  
// This code is contributed by Sam007

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to count all pair that
// hold condition i*arr[i] > j*arr[j]
  
// Return count of pair in given array
// such that i*arr[i] > j*arr[j]
function CountPair($arr , $n )
{
      
    // Initialize result
    $result = 0; 
      
  
    for($i = 0; $i < $n; $i++)
    {
          
        // Generate all pair and increment
        // counter if the hold given condition
        for ($j = $i + 1; $j < $n; $j++)
            if ($i $arr[$i] > $j * $arr[$j] )
                $result ++;
    }
    return $result;
}
  
    // Driver code
    $arr = array(5, 0, 10, 2, 4, 1, 6) ;
    $n = sizeof($arr);
    echo "Count of Pairs : ",
    CountPair($arr, $n);
      
// This code is contributed by m_kit
?>

chevron_right



Output:



Count of Pairs : 5

Time Complexity: O(n2)

An efficient solution of this problem takes O(n log n) time. The idea is based on an interesting fact about this problem that after modifying the array such that every element is multiplied with its index, this problem convert into Count Inversions in an array.
Algorithm :

Given an array 'arr' and it's size 'n'
1) First traversal array element, i goes from 0 to n-1
   a) Multiple each element with its index arr[i] = arr[i] * i 
2) After that step 1. whole process is similar to Count Inversions in an array. 

Below the implementation of above idea

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to count all pair that
// hold condition i*arr[i] > j*arr[j]
#include <bits/stdc++.h>
using namespace std;
  
/* This function merges two sorted arrays and
   returns inversion count in the arrays.*/
int merge(int arr[], int temp[], int left,
                       int mid, int right)
{
    int inv_count = 0;
  
    int i = left; /* index for left subarray*/
    int j = mid;  /* index for right subarray*/
    int k = left; /* ndex for resultant subarray*/
    while ((i <= mid - 1) && (j <= right))
    {
        if (arr[i] <= arr[j])
            temp[k++] = arr[i++];
        else
        {
            temp[k++] = arr[j++];
  
            inv_count = inv_count + (mid - i);
        }
    }
  
    /* Copy the remaining elements of left
     subarray (if there are any) to temp*/
    while (i <= mid - 1)
        temp[k++] = arr[i++];
  
    /* Copy the remaining elements of right
     subarray (if there are any) to temp*/
    while (j <= right)
        temp[k++] = arr[j++];
  
    /* Copy back the merged elements to original
      array*/
    for (i=left; i <= right; i++)
        arr[i] = temp[i];
  
    return inv_count;
}
  
/* An auxiliary recursive function that sorts
   the input array and returns the number of
   inversions in the array. */
int _mergeSort(int arr[], int temp[], int left,
                                      int right)
{
    int mid, inv_count = 0;
    if (right > left)
    {
        /* Divide the array into two parts and call
          _mergeSortAndCountInv() for each of
          the parts */
        mid = (right + left)/2;
  
        /* Inversion count will be sum of inversions in
           left-part, right-part and number of inversions
           in merging */
        inv_count  = _mergeSort(arr, temp, left, mid);
        inv_count += _mergeSort(arr, temp, mid+1, right);
  
        /*Merge the two parts*/
        inv_count += merge(arr, temp, left, mid+1, right);
    }
  
    return inv_count;
}
  
/* This function sorts the input array and
   returns the number of inversions in the
   array */
int countPairs(int arr[], int n)
{
    // Modify the array so that problem reduces to
    // count inversion problem.
    for (int i=0; i<n; i++)
        arr[i] = i*arr[i];
  
    // Count inversions using same logic as
    // below post
    int temp[n];
    return _mergeSort(arr, temp, 0, n - 1);
}
  
// Driver code
int main()
{
    int arr[] = {5, 0, 10, 2, 4, 1, 6};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << "Count of Pairs : "
         << countPairs(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count all pair that
// hold condition i*arr[i] > j*arr[j]
import java.io.*;
  
class GFG 
{
    // This function merges two sorted arrays and
    // returns inversion count in the arrays.
    static int merge(int arr[], int temp[], int left,
                                   int mid, int right)
    {
        int inv_count = 0;
          
        /* index for left subarray*/ 
        int i = left; 
          
        /* index for right subarray*/
        int j = mid; 
        /* ndex for resultant subarray*/
        int k = left; 
          
        while ((i <= mid - 1) && (j <= right))
        {
            if (arr[i] <= arr[j])
                temp[k++] = arr[i++];
            else
            {
                temp[k++] = arr[j++];
      
                inv_count = inv_count + (mid - i);
            }
        }
      
        /* Copy the remaining elements of left
        subarray (if there are any) to temp*/
        while (i <= mid - 1)
            temp[k++] = arr[i++];
      
        /* Copy the remaining elements of right
        subarray (if there are any) to temp*/
        while (j <= right)
            temp[k++] = arr[j++];
      
        // Copy back the merged elements 
        // to original array
        for (i = left; i <= right; i++)
            arr[i] = temp[i];
      
        return inv_count;
    }
      
    /* An auxiliary recursive function 
    that sorts the input array and 
    returns the number of inversions 
    in the array. */
    static int _mergeSort(int arr[], int temp[], 
                               int left,int right)
    {
        int mid, inv_count = 0;
        if (right > left)
        {
            /* Divide the array into two parts and call
            _mergeSortAndCountInv() for each of
            the parts */
            mid = (right + left) / 2;
      
            // Inversion count will be sum of inversions in
            // left-part, right-part and number of inversions
            // in merging 
            inv_count = _mergeSort(arr, temp, left, mid);
            inv_count += _mergeSort(arr, temp, mid+1, right);
      
            /*Merge the two parts*/
            inv_count += merge(arr, temp, left, mid+1, right);
        }
      
        return inv_count;
    }
      
    // This function sorts the input array and
    // returns the number of inversions in the
    // array 
    static int countPairs(int arr[], int n)
    {
        // Modify the array so that problem reduces to
        // count inversion problem.
        for (int i = 0; i < n; i++)
            arr[i] = i * arr[i];
      
        // Count inversions using same logic as
        // below post
        int temp[] = new int [n];
        return _mergeSort(arr, temp, 0, n - 1);
    }
      
    // Driver code
  
    public static void main (String[] args) 
    {
        int arr[] = {5, 0, 10, 2, 4, 1, 6};
        int n = arr.length;
        System.out.print( "Count of Pairs : "
                          + countPairs(arr, n));  
          
    }
}
  
// This code is contributed by vt_m

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to count all 
# pair that hold condition
# i*arr[i] > j*arr[j]
  
# This function merges two 
# sorted arrays and returns 
# inversion count in the arrays.
def merge(arr, temp, left, mid, right):
  
    inv_count = 0
  
    i = left # index for left subarray
    j = mid # index for right subarray
    k = left # ndex for resultant subarray
    while ((i <= mid - 1) and (j <= right)):
      
        if (arr[i] <= arr[j]):
            temp[k] = arr[i]
            i += 1
            k += 1
        else:
          
            temp[k] = arr[j]
            k += 1
            j += 1
  
            inv_count = inv_count + (mid - i)
  
    # Copy the remaining elements of left
    # subarray (if there are any) to temp
    while (i <= mid - 1):
        temp[k] = arr[i]
        i += 1
        k += 1
  
    # Copy the remaining elements of right
    # subarray (if there are any) to temp
    while (j <= right):
        temp[k] = arr[j]
        k += 1
        j += 1
  
    # Copy back the merged elements 
    # to original array
    for i in range(left, right + 1):
        arr[i] = temp[i]
  
    return inv_count
  
# An auxiliary recursive function 
# that sorts the input array and 
# returns the number of inversions
# in the array. 
def _mergeSort(arr, temp, left, right):
  
    inv_count = 0
    if (right > left):
      
        # Divide the array into two parts 
        # and call _mergeSortAndCountInv() 
        # for each of the parts 
        mid = (right + left) // 2
  
        # Inversion count will be sum of 
        # inversions in left-part, right-part x
        # and number of inversions in merging 
        inv_count = _mergeSort(arr, temp, left, mid)
        inv_count += _mergeSort(arr, temp, 
                                mid + 1, right)
  
        # Merge the two parts
        inv_count += merge(arr, temp, left,     
                           mid + 1, right)
  
    return inv_count
  
# This function sorts the input 
# array and returns the number 
# of inversions in the array 
def countPairs(arr, n):
      
    # Modify the array so that problem 
    # reduces to count inversion problem.
    for i in range(n):
        arr[i] = i * arr[i]
  
    # Count inversions using same 
    # logic as below post
    temp = [0] * n
    return _mergeSort(arr, temp, 0, n - 1)
  
# Driver code
if __name__ == "__main__":
    arr = [5, 0, 10, 2, 4, 1, 6]
    n = len(arr)
    print("Count of Pairs : "
           countPairs(arr, n))
             
# This code is contributed 
# by ChitraNayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count all pair that
// hold condition i*arr[i] > j*arr[j]
using System;
  
class GFG 
{
    // This function merges two sorted arrays and
    // returns inversion count in the arrays.
    static int merge(int []arr, int []temp, int left,
                                int mid, int right)
    {
        int inv_count = 0;
          
        /* index for left subarray*/
        int i = left; 
          
        /* index for right subarray*/
        int j = mid; 
        /* ndex for resultant subarray*/
        int k = left; 
          
        while ((i <= mid - 1) && (j <= right))
        {
            if (arr[i] <= arr[j])
                temp[k++] = arr[i++];
            else
            {
                temp[k++] = arr[j++];
      
                inv_count = inv_count + (mid - i);
            }
        }
      
        /* Copy the remaining elements of left
        subarray (if there are any) to temp*/
        while (i <= mid - 1)
            temp[k++] = arr[i++];
      
        /* Copy the remaining elements of right
        subarray (if there are any) to temp*/
        while (j <= right)
            temp[k++] = arr[j++];
      
        // Copy back the merged elements 
        // to original array
        for (i = left; i <= right; i++)
            arr[i] = temp[i];
      
        return inv_count;
    }
      
    /* An auxiliary recursive function 
    that sorts the input array and 
    returns the number of inversions 
    in the array. */
    static int _mergeSort(int []arr, int []temp, 
                            int left,int right)
    {
        int mid, inv_count = 0;
        if (right > left)
        {
            /* Divide the array into two parts and call
            _mergeSortAndCountInv() for each of
            the parts */
            mid = (right + left) / 2;
      
            // Inversion count will be sum of inversions in
            // left-part, right-part and number of inversions
            // in merging 
            inv_count = _mergeSort(arr, temp, left, mid);
            inv_count += _mergeSort(arr, temp, mid+1, right);
      
            /*Merge the two parts*/
            inv_count += merge(arr, temp, left, mid+1, right);
        }
      
        return inv_count;
    }
      
    // This function sorts the input array and
    // returns the number of inversions in the
    // array 
    static int countPairs(int []arr, int n)
    {
        // Modify the array so that problem reduces to
        // count inversion problem.
        for (int i = 0; i < n; i++)
            arr[i] = i * arr[i];
      
        // Count inversions using same logic as
        // below post
        int []temp = new int [n];
        return _mergeSort(arr, temp, 0, n - 1);
    }
      
    // Driver code
  
    public static void Main () 
    {
        int []arr = {5, 0, 10, 2, 4, 1, 6};
        int n = arr.Length;
        Console.WriteLine( "Count of Pairs : "
                        + countPairs(arr, n)); 
          
    }
}
  
// This code is contributed by anuj_67.

chevron_right



Output:

Count of Pairs : 5

Time Complexity: O(n log n)

This article is contributed by Nishant_Singh (Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : Sam007, jit_t, vt_m, Ita_c