Count number of pairs with positive sum in an array

Given an array arr[] of N integers, the task is to count the number of pairs with positive sum.

Examples:

Input: arr[] = {-7, -1, 3, 2}
Output: 3
Explanation:
The pairs with positive sum are: {-1, 3}, {-1, 2}, {3, 2}.



Input: arr[] = {-4, -2, 5}
Output: 2
Explanation:
The pairs with positive sum are: {-4, 5}, {-2, 5}.

Naive Approach:
A naive approach is to traverse each element and check if there is another number in the array arr[] which can be added to it to give the positive-sum or not.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// Naive approach to count pairs
// with positive sum.
#include <bits/stdc++.h>
using namespace std;
  
// Returns number of pairs in
// arr[0..n-1] with positive sum
int CountPairs(int arr[], int n)
{
    // Initialize result
    int count = 0;
  
    // Consider all possible pairs
    // and check their sums
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
  
            // If arr[i] & arr[j]
            // form valid pair
            if (arr[i] + arr[j] > 0)
                count += 1;
        }
    }
  
    return count;
}
  
// Driver's Code
int main()
{
    int arr[] = { -7, -1, 3, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call to find the
    // count of pairs
    cout << CountPairs(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the above approach
class GFG 
{
          
    // Naive approach to count pairs
    // with positive sum.
      
    // Returns number of pairs in
    // arr[0..n-1] with positive sum
    static int CountPairs(int arr[], int n)
    {
        // Initialize result
        int count = 0;
      
        // Consider all possible pairs
        // and check their sums
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
      
                // If arr[i] & arr[j]
                // form valid pair
                if (arr[i] + arr[j] > 0)
                    count += 1;
            }
        }
      
        return count;
    }
      
    // Driver's Code
    public static void main (String[] args)
    {
        int []arr = { -7, -1, 3, 2 };
        int n = arr.length;
      
        // Function call to find the
        // count of pairs
        System.out.println(CountPairs(arr, n));
    }
}
  
// This code is contributed by Yash_R

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Naive approach to count pairs
# with positive sum.
  
# Returns number of pairs in
# arr[0..n-1] with positive sum
def CountPairs(arr, n) :
    # Initialize result
    count = 0;
  
    # Consider all possible pairs
    # and check their sums
    for i in range(n) :
        for j in range( i + 1, n) :
  
            # If arr[i] & arr[j]
            # form valid pair
            if (arr[i] + arr[j] > 0) :
                count += 1;
  
    return count;
  
# Driver's Code
if __name__ == "__main__" :
  
    arr = [ -7, -1, 3, 2 ];
    n = len(arr);
  
    # Function call to find the
    # count of pairs
    print(CountPairs(arr, n));
      
# This code is contributed by Yash_R

chevron_right


Output:

3

Time Complexity: O(N2)

Efficient Approach:
The idea is to use the Two Pointers Technique. Following are the steps:

  1. Sort the given array arr[] in increasing order.
  2. Take two pointers. one representing the first element and second representing the last element of the sorted array.
  3. If the sum of elements at these pointers is greater than 0, then the difference between the pointers will give the count of pairs with positive-sum for the element at second pointers. Decrease the second pointer by 1.
  4. Else increase the first pointers by 1.
  5. Repeat the above steps untill both pointers converge towards each other.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to count the
// pairs with positive sum
#include <bits/stdc++.h>
using namespace std;
  
// Returns number of pairs
// in arr[0..n-1] with
// positive sum
int CountPairs(int arr[], int n)
{
    // Sort the array in
    // increasing order
    sort(arr, arr + n);
  
    // Intialise result
    int count = 0;
  
    // Intialise first and
    // second pointer
    int l = 0, r = n - 1;
  
    // Till the pointers
    // doesn't converge
    // traverse array to
    // count the pairs
    while (l < r) {
  
        // If sum of arr[i] &&
        // arr[j] > 0, then the
        // count of pairs with
        // positive sum is the
        // difference between
        // the two pointers
        if (arr[l] + arr[r] > 0) {
  
            // Increase the count
            count += (r - l);
            r--;
        }
        else {
            l++;
        }
    }
    return count;
}
  
// Driver's Code
int main()
{
    int arr[] = { -7, -1, 3, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call to count
    // the pairs with positive
    // sum
    cout << CountPairs(arr, n);
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count the 
# pairs with positive sum 
  
# Returns number of pairs 
# in arr[0..n-1] with 
# positive sum 
def CountPairs(arr, n) : 
  
    # Sort the array in 
    # increasing order 
    arr.sort()
  
    # Intialise result 
    count = 0
  
    # Intialise first and 
    # second pointer 
    l = 0; r = n - 1
  
    # Till the pointers 
    # doesn't converge 
    # traverse array to 
    # count the pairs 
    while (l < r) :
  
        # If sum of arr[i] && 
        # arr[j] > 0, then the 
        # count of pairs with 
        # positive sum is the 
        # difference between 
        # the two pointers 
        if (arr[l] + arr[r] > 0) :
  
            # Increase the count 
            count += (r - l); 
            r -= 1
          
        else :
            l += 1
              
    return count; 
  
# Driver's Code 
if __name__ == "__main__"
  
    arr = [ -7, -1, 3, 2 ]; 
    n = len(arr); 
  
    # Function call to count 
    # the pairs with positive 
    # sum 
    print(CountPairs(arr, n)); 
  
# This code is contributed by Yash_R

chevron_right


Output:

3

Time Complexity: O(N*log N)

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Yash_R