Problem 308
Count Triplets with Smaller Sum
Medium · 20 pts · Array, Two Pointers, Sorting
Problem
Count the triplets of positions (i, j, k) with i < j < k such that A[i] + A[j] + A[k] is strictly less than the given value S. Triplets are counted by position, so equal values at different positions form different triplets. A brute-force check of every triplet is too slow for large N; sorting and two pointers solve it in O(N²).
Input
The first line contains N and S. The second line contains N integers.
Output
Print the number of triplets with a sum less than S.
Constraints
3 <= N <= 3000; -100000 <= A[i], S <= 100000
Example input
4 2 -2 0 1 3
Example output
2
Explanation
With S = 2 in -2 0 1 3, the triplets (-2, 0, 1) with sum -1 and (-2, 0, 3) with sum 1 are below 2; the other two triplets are not, so the answer is 2.