I faced this problem in a hackathon but couldn't figure out where I was going wrong.
The problem statement was
Count the number of subsequences in an array where the difference of the first and last element is <= K
Each subsequence is contiguous
Input: 11 5 2 15 25
Output: 6
Explanation: {11}, {5}, {2}, {15}, {25}, {5, 2}
I believe they were considering a single element as a valid subsequence so what I tried to return the length of the array + the count.
int getCount(int *a, int n, int k){
sort(a, a + n);
int c = 0;
for(int i=0; i<n; i++){
int j = i + 1;
while(j < n and a[j] - a[i] <= k){
c+=1;
j+=1;
}
}
return n + c;
}
I've tried sorting but it still timed out!