Problem 375
Valid Triangle Number
Medium · 20 pts · Array, Two Pointers, Binary Search, Sorting
Problem
Count the triplets of positions i < j < k whose values can be the side lengths of a triangle. Three lengths form a triangle exactly when each one is smaller than the sum of the other two; for sorted lengths a <= b <= c it is enough to check a + b > c. Sides of length 0 never form a triangle. Triplets are counted by position, so equal values at different positions are different triplets.
Input
First line: N. Second line: N non-negative integers.
Output
Print the number of valid triangles.
Constraints
1 <= N <= 1000; 0 <= A[i] <= 1000
Example input
4 2 2 3 4
Example output
3
Explanation
From 2 2 3 4, the triplets (2, 3, 4) using the first 2, (2, 3, 4) using the second 2, and (2, 2, 3) form triangles. (2, 2, 4) does not, because 2 + 2 is not greater than 4. So the answer is 3.