Problem · Array

Increasing-Value Triplets Under a Threshold

Learn this problem
MediumIBM logoIBMINTERNOA
See IBM hiring insights

Problem 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[]) → long

Examples

Example 1

t = 8d = [1, 2, 3, 4, 5]return = 4

The four valid value triplets are:

  • (1, 2, 3), whose sum is 6.
  • (1, 2, 4), whose sum is 7.
  • (1, 2, 5), whose sum is 8.
  • (1, 3, 4), whose sum is 8.

Example 2

t = 7d = [4, 1, 2]return = 1

The 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 = 1

The 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 d are distinct.
  • 0 < d[i] < 10^9.
  • 0 < t < 3 * 10^9.

More IBM problems

drafts saved locally
public long triplets(long t, int[] d) {
  // Write your code here.
}
t8
d[1, 2, 3, 4, 5]
expected4
checking account