Count number of pairs with positive sum in an array
Last Updated :
30 Nov, 2023
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++
// 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;
}
Java
// 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
Python3
# 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
C#
// C# implementation of the above approach
using System;
class GFG {
// Naive approach to count pairs with positive sum.
// Returns the number of pairs in arr[0..n-1] with a
// 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] and arr[j] form a 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
Console.WriteLine(CountPairs(arr, n));
}
}
JavaScript
function CountPairs(arr, n) {
// Initialize the result
let count = 0;
// Consider all possible pairs and check their sums
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// If arr[i] and arr[j] form a valid pair
if (arr[i] + arr[j] > 0) {
count++;
}
}
}
return count;
}
// Driver's Code
const arr = [-7, -1, 3, 2];
const n = arr.length;
// Function call to find the count of pairs
console.log(CountPairs(arr, n));
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The idea is to use the Two Pointers Technique
Step-by-step approach:
- Sort the given array arr[] in increasing order.
- Take two pointers. one representing the first element and second representing the last element of the sorted array.
- 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.
- Else increase the first pointers by 1.
- Repeat the above steps untill both pointers converge towards each other.
Below is the implementation of the above approach:
C++
// 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;
}
Java
import java.util.Arrays;
public class Main {
// Returns the number of pairs in arr[0..n-1] with a positive sum
static int countPairs(int arr[], int n) {
// Sort the array in increasing order
Arrays.sort(arr);
// Initialize result
int count = 0;
// Initialize first and second pointers
int l = 0, r = n - 1;
// Traverse the array to count the pairs until the pointers converge
while (l < r) {
// If the sum of arr[i] and 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
public static void main(String[] args) {
int arr[] = { -7, -1, 3, 2 };
int n = arr.length;
// Function call to count the pairs with positive sum
System.out.println(countPairs(arr, n));
}
}
Python3
# 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
C#
using System;
class GFG {
public static int countPairs(int[] arr)
{
// Sort the array in increasing order
Array.Sort(arr);
// Initialize the result
int count = 0;
// Initialize the left and right pointers
int l = 0;
int r = arr.Length - 1;
// Traverse the array to count the pairs
while (l < r) {
// If the sum of arr[i] and arr[j] > 0,
// then the count of pairs with a positive sum
// is the difference between the two pointers
if (arr[l] + arr[r] > 0) {
count += r - l;
r--;
}
else {
l++;
}
}
return count;
}
public static void Main(string[] args)
{
// Example usage:
int[] arr = new int[] { -7, -1, 3, 2 };
int result = countPairs(arr);
Console.WriteLine(result);
}
}
JavaScript
function countPairs(arr) {
// Sort the array in increasing order
arr.sort((a, b) => a - b);
// Initialize the result
let count = 0;
// Initialize the left and right pointers
let l = 0;
let r = arr.length - 1;
// Traverse the array to count the pairs
while (l < r) {
// If the sum of arr[i] and arr[j] > 0,
// then the count of pairs with a positive sum
// is the difference between the two pointers
if (arr[l] + arr[r] > 0) {
count += r - l;
r--;
} else {
l++;
}
}
return count;
}
// Example usage:
const arr = [-7, -1, 3, 2];
const result = countPairs(arr);
console.log(result);
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read