Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to find out the number of pairs in an array that satisfy a given condition
Suppose, we are given n numbers in array nums. We have to choose a pair of two numbers from the array, and there is a condition that the difference of their positions in the array is equal to the sum of the two numbers. There can be a total of n(n - 1)/2 number of total pairs from the given array of numbers. We have to find out the total number of such pairs from the array.
So, if the input is like n = 8, nums = {4, 2, 1, 0, 1, 2, 3, 3}, then the output will be 13.
There can be 13 such pairs in the array.
To solve this, we will follow these steps −
Define an array vals(n) for initialize i := 0, when i < n, update (increase i by 1), do: vals[i] := i + 1 - nums[i] sort the array vals res := 0 for initialize i := 0, when i < n, update (increase i by 1), do: k := nums[i] + i + 1 res := res + (position of first occurrence of a value not less than k in array vals - position of first occurrence of a value not greater than k in array vals) return res
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
int solve(int n, vector<int> nums){
vector<int> vals(n);
for( int i = 0; i < n; i++)
vals[i] = i + 1 - nums[i];
sort(vals.begin(), vals.end());
int res = 0;
for( int i = 0; i < n; i++ ) {
int k = nums[i] + i + 1;
res += upper_bound(vals.begin(), vals.end(), k) - lower_bound(vals.begin(), vals.end(), k);
}
return res;
}
int main() {
int n = 8;
vector<int> nums = {4, 2, 1, 0, 1, 2, 3, 3};
cout<< solve(n, nums);
return 0;
}
Input
8, {4, 2, 1, 0, 1, 2, 3, 3}
Output
13
Advertisements