Three Dishes Under the Calorie Cap

medium two-pointers sorting arrays 1500 ms · 256 MB

Three Dishes Under the Calorie Cap

The campus canteen sells n dishes, numbered 1 to n. Dish i has a_i calories.

A new "triple combo" deal lets a diner pick three different dishes (three different menu numbers; a dish cannot be counted twice even if another dish happens to have the same calorie count). The combo is allowed only if the total calories of the three chosen dishes is strictly less than a daily cap T.

Two combos are considered different if the set of three dish numbers differs — the order in which the dishes are eaten does not matter, so {dish 2, dish 5, dish 9} and {dish 9, dish 2, dish 5} are the same combo and must be counted once.

Count how many different combos satisfy the cap.

Input

The first line contains two integers n and T (3 ≤ n ≤ 5000, 1 ≤ T ≤ 3·10^9).

The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the calorie count of each dish. Calorie counts are not necessarily distinct.

Output

Print a single integer: the number of combos of three distinct dish numbers whose calories sum to strictly less than T. The answer can be large, so use a 64-bit integer type.

Notes

In the first example, the dishes have calories [3, 1, 4, 1, 5] and the cap is T = 7. The qualifying combos (by calorie value, ignoring which identical-valued dish is picked) are the index-triples whose three calorie values sum below 7: for instance dishes with calories 1, 1, 3 (sum 5) and 1, 1, 4 (sum 6) qualify, while 1, 3, 4 (sum 8) does not. Working this out by hand over every one of the index-triples gives the printed answer.

Example 1

Input

5 7
3 1 4 1 5

Output

2

Example 2

Input

4 100
10 20 30 40

Output

4

Hints · reveal one at a time if you're stuck

Hint 1

With n up to 5000, checking all triples is far too slow. Could you fix one dish and count the pairs for the other two in a faster way?

Hint 2

Sort the calorie values first. Once they are sorted, a fixed first dish plus a pair of the others can be counted with a sweep from both ends, the way you would look for a pair that sums to a target.

Hint 3

In the sweep, when the sum of the fixed dish and the two ends is already under the cap, every dish between the two ends can also be the upper partner, so you can count them all at once. Remember the cap is strict, and the answer needs a 64-bit total.

report an issue Prefer your own editor? sooks prep 84 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.