C++ 0976.cpp
class Solution {
public:
int largestPerimeter(vector<int>& nums) {
sort(nums.begin(), nums.end());
reverse(nums.begin(), nums.end());
int maxx = 0;
for (int x = 0; x < nums.size(); x++)
{
int a = nums[x];
if (3*a <= maxx)
break;
for (int y = x+1; y < nums.size(); y++)
{
int b = nums[y];
if (a+b+b <= maxx)
break;
for (int z = y+1; z < nums.size(); z++)
{
int c = nums[z];
if (b + c <= a)
break;
if (a+b+c <= maxx)
break;
maxx = a+b+c;
}
}
}
return maxx;
}
};
Difficulty
and has an acceptance rate of about 62% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Math
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The largestPerimeter method receives a mutable reference to a vector of integers that represent side lengths. Its goal is to find the greatest possible perimeter of a non-degenerate triangle that can be formed from any three distinct elements of the input. If no such triangle exists, the method returns 0. The implementation follows a three-level nested iteration after arranging the data in descending order, and it incorporates several early-exit checks that prune the search space.
Key Steps
Sorting and arranging in descending order
The first two statements prepare the data for efficient scanning.
sort(nums.begin(), nums.end());
reverse(nums.begin(), nums.end());
sort orders the elements in non-decreasing order, and reverse flips the sequence so that the largest values appear first. This ordering enables the algorithm to consider the biggest possible sides early and to apply monotonic break conditions safely.
Selecting the longest side (outer loop)
The outermost loop iterates over each candidate for the longest side a.
for (int x = 0; x < nums.size(); x++)
{
int a = nums[x];
if (3*a <= maxx)
break;
…
}
The loop variable x indexes the vector, and a stores the current side length. The guard if (3*a <= maxx) break; stops further exploration once three copies of the current a could not improve the best perimeter already found (maxx). Because the array is descending, any later a will be smaller, making the condition sufficient to terminate the outer loop early.
Choosing the middle side (middle loop)
For each a, the algorithm picks a second side b that is strictly smaller in index.
for (int y = x+1; y < nums.size(); y++)
{
int b = nums[y];
if (a + b + b <= maxx)
break;
…
}
Here b is the next candidate side. The test if (a + b + b <= maxx) break; leverages the fact that the third side c cannot exceed b (due to descending order). If even the sum of a and two copies of b fails to beat maxx, no further b values (which are smaller) can succeed, so the middle loop exits early.
Picking the smallest side (inner loop)
The innermost loop examines each possible third side c.
for (int z = y+1; z < nums.size(); z++)
{
int c = nums[z];
if (b + c <= a)
break;
if (a + b + c <= maxx)
break;
maxx = a + b + c;
}
The first condition if (b + c <= a) break; enforces the triangle inequality: for a valid triangle the sum of the two shorter sides must exceed the longest side. Because c only gets smaller as z increases, once this inequality fails it will never hold again, allowing an immediate exit from the inner loop. The second condition if (a + b + c <= maxx) break; stops the search when the current perimeter cannot improve the best result. When both checks pass, the perimeter a + b + c is larger than any previously recorded value, and maxx is updated accordingly.
Returning the result
After all feasible triples have been examined (or pruned), the method returns the maximum perimeter found.
return maxx;
If no triple satisfied the triangle inequality, maxx remains at its initial value 0, which the caller interprets as “no triangle possible”.
Edge Cases Handled
The algorithm gracefully handles inputs that contain fewer than three elements because the outer loop’s range is bounded by nums.size(). When the size is less than three, the inner loops never execute, leaving maxx at 0.
When the vector consists entirely of values that cannot satisfy the triangle inequality (for example, a monotonic decreasing sequence where each element is at least the sum of the two following ones), the inner break if (b + c <= a) break; triggers immediately, preventing unnecessary iterations.
If the vector contains many duplicate large values, the early-exit condition if (3*a <= maxx) break; ensures that once a maximal perimeter has been discovered, any further exploration of equal or smaller a values stops, even when duplicates could otherwise cause redundant checks.
Performance Optimizations
The most noticeable optimization is the descending ordering of the input, which makes the three nested loops amenable to monotonic break statements. By guaranteeing that each subsequent candidate side is not larger than the previous, the algorithm can safely conclude that once a condition fails for a given index, it will continue to fail for all larger indices.
The outermost early-exit if (3*a <= maxx) break; eliminates entire sections of the search space once the current largest side is too small to improve the best perimeter.
Similarly, the middle loop’s guard if (a + b + b <= maxx) break; leverages the fact that the third side cannot exceed b, allowing the loop to stop without scanning the remaining elements.
Inside the innermost loop, the triangle-inequality check if (b + c <= a) break; provides a decisive cut-off: as soon as the sum of the two shorter sides falls short of the longest side, no further c values can satisfy the inequality, so the loop terminates instantly.
Finally, the second inner condition if (a + b + c <= maxx) break; prevents the algorithm from updating maxx with a non-improving perimeter and avoids needless continuation of the innermost loop once the current combination cannot beat the best known result.
Collectively, these early-exit strategies reduce the effective number of examined triples dramatically, especially for large inputs with many elements that cannot form a triangle, yielding a runtime that is far better than the naïve cubic enumeration.
ELI5 - Simplified Explanation
Imagine you have a big bucket full of wooden sticks of all different lengths, and you want to build a triangle using three of them. To make sure the sticks fit together just right, there is a special rule where the two shorter sticks must add up to be longer than the longest stick.
The computer starts by putting all the sticks in a line from the longest to the shortest so that it is easier to find the big ones first. It looks at three sticks at a time to see if they can form a triangle. It checks the rule by adding the lengths of the two smaller sticks together and comparing them to the longest one.
If it finds a good set of sticks that makes a triangle, it measures how long the outside edge of that triangle is by adding all three sides together. Then, it remembers that measurement. As it keeps looking at other combinations of sticks, it always checks if a new triangle is bigger than the one it found before. If it finds a bigger one, it keeps the new measurement instead. After it goes through all the different sticks, it knows which triangle had the longest edge of them all.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | C | Rust | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | Java | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| pruthvikp | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| withaarzoo | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | Java | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| pruthvikp | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 812: Largest Triangle Area
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality