Largest Triangular Pen

EasyGreedy

Problem

A farmer has fence panels of lengths lengths. Choose exactly three panels to build a triangular pen with positive area.

Return the largest possible perimeter, or 0 if no three panels can form such a triangle.

Example 1

Input:
lengths = [3, 6, 2, 3]
Output:
8

6, 3, 3 is degenerate (6 = 3 + 3); 3, 3, 2 works with perimeter 8.

Example 2

Input:
lengths = [1, 2, 1, 10]
Output:
0

Constraints

  • 3 ≤ lengths.length ≤ 10^4
  • 1 ≤ lengths[i] ≤ 10^6

Hint

Show the first hint

With sides a ≤ b ≤ c, which single inequality decides whether they form a triangle?

Walkthrough

How to approach it

01Clarify before coding

  • Does a flat triangle (a + b = c) count? No: the area must be positive, so a + b > c strictly.
  • Exactly three panels? Yes, and each panel is used at most once.
  • What if nothing works? Return 0.

02Brute force

Check all triples and keep the largest valid perimeter.

Cost: O(n³), about 1.7 · 10^11 triples for n = 10^4.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.