Problem 336850 · hard · Level 03 Linear Management & Searching

Three Poles for a Tent Frame

two pointers · sorting · counting · triangle inequality

A camping shop keeps a bin of poles with lengths poles. A triangular tent frame needs three different poles (different positions in the list; equal lengths are fine) whose lengths a, b, c form a triangle with positive area: each length is strictly less than the sum of the other two. Return how many sets of three positions {i, j, k} make a valid frame.

Examples

Input:  poles = [5, 2, 4, 3]
Output: 3
Explanation: (5,2,4), (5,4,3) and (2,4,3) work; in (5,2,3) the two short poles only reach 5.

Input:  poles = [1, 2, 3, 5, 9]
Output: 0
Explanation: 1 + 2 = 3 and 2 + 3 = 5 only equal the longest pole (a flat frame), and every other set falls short.

Input:  poles = [5, 5, 5, 1, 10]
Output: 4
Explanation: (5,5,5) and the three sets (5,5,1). A 10 needs the other two to sum above 10.

Constraints

  • 0 <= len(poles) <= 2000
  • 1 <= poles[i] <= 10**6
  • Fewer than three poles give 0.

Goals

  • Reduce a three-condition test to a single condition by sorting
  • Count many valid pairs at once when one pointer move settles a whole block
Starting Python…