Count number of triplets in an array having sum in the range [a,b] in C++


We are given an array of integers, Arr[] and two variables a and b to define a range [a,b]. The goal is to find the number of triplets whose sum lies in between this range [a,b].

We will do this by using three for loops. Increment count if arr[i]+arr[j]+arr[k]>=a and arr[i]+arr[j]+arr[k]<=b. Where 0<=i<=n-2, i<j<n-1, j<k<n. Where n is no. of elements in Arr[].

Let’s understand with examples.

Input − arr[]= { 1,2,3,4,5 }, N=5, L=2, R=8

Output − Number of triplets − 4

Explanation

Triplets with sum>=2 and sum<=8
(1,2,3) → 6
(1,2,4) → 7
(1,2,5) → 8
(1,3,4) → 8
Total triplets: 4

Input − arr[]= {2,2,2,2,2}, N=5, L=2, R=5

Output − Number of triplets − 0

Explanation

Every triplet will have the sum 6. Which is not in the range [2,5]

Total triplets: 0

Approach used in the below program is as follows

  • We take an integer array Arr[] initialized with random numbers.

  • Take variables L and R for defining a range [L,R]. N stores the length of Arr[].

  • Function countTriplets(int arr[],int n,int a,int b) takes an array, its length and range variables as input and returns the triplets whose sum lies in this range.

  • Take the initial variable count as 0 for the number of triplets.

  • Take the initial variable sum as the sum of each triplet. Initially 0.

  • Traverse array using three for loops for each element of the triplet.

  • Outermost loop from 0<=i<n-2, inner loop i<j<n-1, innermost j<k<n.

  • Calculate sum=arr[i]+arr[j]+arr[k]. If a<=sum<=b then increment count.

  • At the end of all loops count will have a total number of triplets that meet the condition.

  • Return the count as desired result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int countTriplets(int arr[],int n,int a,int b){
   int count = 0;
   int sum=0;
   for (int i = 0; i < n-2; i++){
      for (int j = i+1; j < n-1; j++){
         for (int k = j+1; k < n; k++){
            sum=arr[i]+arr[j]+arr[k];
            if ( sum>=a && sum<=b) //check{
               count++;
               // cout<<endl<<"a :"<<arr[i]<<" b :"<<arr[j]<<" c :"<<arr[k]; //to print
            }
         }
      }
   }
   return count;
}
int main(){
   int Arr[]={ 5,4,3,6,8,2 };
   int L=9;
   int R=15;
   int N=6; //length of array
   cout <<endl<< "Number of triplets : "<<countTriplets(Arr,N,L,R);
   return 0;
}

Output

If we run the above code it will generate the following output −

Number of triplets : 14

Updated on: 29-Aug-2020

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements