Problem · Array
Increasing-Value Triplets Under a Threshold
Learn this problemProblem statement
Given an array of distinct integers d and a threshold t, return the number of triplets of distinct indices (a, b, c) that satisfy both conditions:
d[a] < d[b] < d[c].d[a] + d[b] + d[c] <= t.
The indices identify three distinct elements. Their original positions do not need to satisfy a < b < c; the tuple is ordered by the selected values.
Use 64-bit arithmetic for t, each sum, and the returned count.
Implement triplets(long t, int[] d).
Function
triplets(t: long, d: int[]) → longExamples
Example 1
t = 8d = [1, 2, 3, 4, 5]return = 4The four valid value triplets are:
(1, 2, 3), whose sum is6.(1, 2, 4), whose sum is7.(1, 2, 5), whose sum is8.(1, 3, 4), whose sum is8.
Example 2
t = 7d = [4, 1, 2]return = 1The selected values (1, 2, 4) have sum 7. Their original indices are (1, 2, 0), so they count even though those positions are not increasing.
Example 3
t = 2500000000d = [800000000, 800000001, 800000002]return = 1The only possible triplet sums to 2400000003, which does not exceed 2500000000. The threshold is greater than 2^31 - 1, so it requires a 64-bit type.
Constraints
1 <= d.length <= 10^4.- All values in
dare distinct. 0 < d[i] < 10^9.0 < t < 3 * 10^9.