Count pairs in a sorted array whose sum is less than x

QUESTION

Count pairs in a sorted array whose sum is less than x.

“TESTCASE_1”: “5 4\n1 6 7 8 9\n###—###SEPERATOR—###—\n0”, “TESTCASE_2”: “6 8\n4 4 5 3 1 10\n###—###SEPERATOR—###—\n10”, “TESTCASE_3”: “8 4\n2 3 8 7 9 1 0 12\n###—###SEPERATOR—###—\n11”, “TESTCASE_4”: “4 8\n1 2 3 5\n###—###SEPERATOR—###—\n5”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <iostream>
using namespace std;

int find(int arr[],int n,int x)
{
    int l = 0, r = n-1;
    int result = 0;
    while (l < r)
    {
        if (arr[l] + arr[r] < x){
            result += (r - l);
            l++;
        }
        else
            r--;
    }
    return result;
}

int main()
{
	int n,x;
  	cin>>n>>x;
  	int a[n];
  	for(int i=0;i<n;i++)
      cin>>a[i];
  	cout<<find(a,n,x);
	return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
100% Free SEO Tools - Tool Kits PRO