Given an array arr[] of distinct integers of size N and a value sum, the task is to find the count of triplets (i, j, k), having (i<j<k) with the sum of (arr[i] + arr[j] + arr[k]) smaller than the given value sum.
Time : O(n^2)
Space : O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution{ public: longlongcountTriplets(longlong arr[], int n, longlong sum){ longlong res = 0; sort(arr, arr + n); for(int i = 0; i < n; i++) { longlong l = i + 1, r = n - 1, target = sum - arr[i]; while(l < r) { while(l < r and arr[l] + arr[r] >= target) r--; if(l < r) res += (r - l); l++; } } return res; } };