Parcel-delivery app~15 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-976greedy · sorting
A depot makes triangular braces for pallets from three straps joined end to end. A brace holds its shape only when the two shorter straps together are longer than the longest strap. Two straps that exactly equal the longest give a flat brace, which is not allowed. Each strap in stock has a length in millimetres, and each strap is used at most once.
Write largest_frame_perimeter(straps).
straps[i] is the length of strap i.0 when no three straps can form a brace.Input: straps = [2, 9, 3, 5, 4]
Output: 12Sort the straps from longest to shortest. Then test each strap against the two straps right after it.
| Longest | Next two | Their sum | Frame? |
|---|---|---|---|
| 9 | 5, 4 | 9 | no: 9 is not below 9 |
| 5 | 4, 3 | 7 | yes: 5 < 7, perimeter 12 |
The straps 5, 4 and 3 form a brace, so the largest perimeter is 12.
Input: straps = [1, 2, 10]
Output: 0The two shorter straps total 3, which is less than 10, so the answer is 0.
Input: straps = [6, 6, 6, 6]
Output: 18Any three straps work, and the perimeter is 18.
0 ≤ straps.length ≤ 100,000 (straps in stock)1 ≤ straps[i] ≤ 1,000,000,000 (millimetres)Testing every triple of straps costs about n × n × n, which is 10^15 at n = 100,000. Sorting costs n log n, and one pass after it costs n.