I was solving a task:
Input n,m,k
– integer numbers and integer array arr
of size n
The pair of elements in arr
is valid if two conditions are true
std::abs(arr[i], arr[j]) <= m
arr[i] + arr[j] <= k
Output
– number of valid pairs
Example:
Input
4 1 5
1 3 2 3
Output
3
The output is 3, because of pairs (1,2) (3, 2) and (2, 3)
My code is working. But it’s time complexity is O(N^2) and I have a TIME LIMIT error
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main() {
int n, m, k;
cin >> n >> m >> k;
vector<int> arr(n);
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
sort(begin(arr), end(arr));
int res = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (arr[i] + arr[j] <= k and abs(arr[i] - arr[j]) <= m) {
res++;
} else {
break;
}
}
}
cout << res;
return 0;
}
I think that I should apply idea of sorting, how to reduce time complexity of my code? I guess it should be O(N*logN)