Given an array, A, having N integers A 1 , A 2 , . . . , A N. Two elements of the array A i and A j are called similar iff A i = A j + 1 or A j = A i + 1. Also, the similarity follows transitivity. If
and are similar and and are similar, then and are also similar.
Note: , , and are all distinct.
You need to find the number of pairs of indices such that and is similar to .
Example:
Input: n = 8, a = [1,3,5,7,8,2,5,7]
Output: 6
Approach
C++
#include <bits/stdc++.h>using namespace std;long long pairsHavingSimiElements(long long n, long long a[]){sort(a, a + n);long long cnt = 0, ans = 0;long long y = 0, i = 0;while (i < n){if (i < n - 1 && a[i] + 1 == a[i + 1]){cnt++;}else if (i < n - 1 && a[i] == a[i + 1]){cnt++;y++;}else{if (y != cnt)ans += cnt * (cnt + 1) / 2;cnt = 0;y = 0;}i++;}return ans;}int main(){long long n = 8;long long a[n] = {1, 3, 5, 7, 8, 2, 5, 7};cout << pairsHavingSimiElements(n, a) << "\n";return 0;}
No comments:
Post a Comment