Suppose we have an array A with n elements, and another number d. According to the regulations of Dreamland's army, a reconnaissance unit should have exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. There are n soldiers whose heights are stored in the array A. Some soldiers are of the same height. We have to find how many ways exist to form a reconnaissance unit from these n soldiers.
So, if the input is like A = [10, 20, 50, 60, 65]; d = 10, then the output will be 6, because (10, 20), (20, 10), (50, 60), (60, 50), (60, 65), (65, 60) are the possible units.
Steps
To solve this, we will follow these steps −
ans := 0 for initialize i := 1, when i < size of A, update (increase i by 1), do: for initialize j := 0, when j < i, update (increase j by 1), do: if |A[i] - A[j]| <= d, then: (increase ans by 1) return ans * 2
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A, int d){
int ans = 0;
for (int i = 1; i < A.size(); i++)
for (int j = 0; j < i; j++)
if (abs(A[i] - A[j]) <= d)
ans++;
return ans * 2;
}
int main(){
vector<int> A = { 10, 20, 50, 60, 65 };
int d = 10;
cout << solve(A, d) << endl;
}Input
{ 10, 20, 50, 60, 65 }, 10Output
6