Pair sum in array
Given array/list can contain duplicate elements.
The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
First line of each test case or query contains an integer 'N' representing the size of the first array/list.
Second line contains 'N' single space separated integers representing the elements in the array/list.
Third line contains an integer 'num'.
For each test case, print the total number of pairs present in the array/list.
Output for every test case will be printed in a separate line.
1 <= t <= 10^2
0 <= N <= 10^4
0 <= num <= 10^9
Time Limit: 1 sec
1
9
1 3 6 2 5 4 3 2 4
7
7
2
9
1 3 6 2 5 4 3 2 4
12
6
2 8 10 5 -2 5
10
0
2
Since there doesn't exist any pair with sum equal to 12 for the first query, we print 0.
For the second query, we have 2 pairs in total that sum up to 10. They are, (2, 8) and (5, 5).
#include <iostream>#include <algorithm>using namespace std;
#include "solution.h"
int main(){ int t; cin >> t;
while (t--) { int size; int x;
cin >> size; int *input = new int[size];
for (int i = 0; i < size; i++) { cin >> input[i]; }
cin >> x;
cout << pairSum(input, size, x) << endl;
delete[] input; } return 0;}
int pairSum(int *arr, int n, int num){ //Write your code here int sum=0; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(arr[i]+arr[j]==num) sum++; } } return sum;}
Comments
Post a Comment