← Home

976. Largest Perimeter Triangle

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
976

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 976. Largest Perimeter Triangle, the solution in this repository is mainly a greedy solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are largestPerimeterFromSorted, largestPerimeter.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(NlogN), where N is the length of A.
  • Space: O(1).

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.
03
04If it is impossible to form any triangle of non-zero area, return 0.
05
06 
07
08Example 1:
09
10Input: [2,1,2]
11Output: 5
12Example 2:
13
14Input: [1,2,1]
15Output: 0
16Example 3:
17
18Input: [3,2,3,4]
19Output: 10
20Example 4:
21
22Input: [3,6,2,3]
23Output: 8
24 
25
26Note:
27
283 <= A.length <= 10000
291 <= A[i] <= 10^6
30**/
31
32/**
33Approach 1: Sort
34Intuition
35
36Without loss of generality, say the sidelengths of the triangle are a≤b≤c. 
37The necessary and sufficient condition for these lengths to form a triangle of non-zero area is a+b>c.
38
39Say we knew cc already.
40There is no reason not to choose the largest possible a and b from the array. 
41If a+b>c, then it forms a triangle, otherwise it doesn't.
42
43Algorithm
44
45This leads to a simple algorithm: Sort the array. 
46For any c in the array, we choose the largest possible a≤b≤c: 
47these are just the two values adjacent to c. 
48If this forms a triangle, we return the answer.
49**/
50
51/**
52Complexity Analysis
53Time Complexity: O(NlogN), where N is the length of A.
54Space Complexity: O(1). 
55**/
56
57//Runtime: 56 ms, faster than 64.97% of C++ online submissions for Largest Perimeter Triangle.
58//Memory Usage: 10.7 MB, less than 99.20% of C++ online submissions for Largest Perimeter Triangle.
59
60class Solution {
61public:
62    int largestPerimeterFromSorted(vector<int>& A){
63        int cur = A.size();
64        
65        while(cur >= 3 && A[cur-3] + A[cur-2] <= A[cur-1]){
66            cur--;
67        }
68        
69        if(cur < 3){
70            return 0;
71        }
72        
73        return A[cur-3] + A[cur-2] + A[cur-1];
74    }
75    
76    int largestPerimeter(vector<int>& A) {
77        sort(A.begin(), A.end());
78        return largestPerimeterFromSorted(A);
79    }
80};

Cost

Complexity

Time
O(NlogN), where N is the length of A.
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(1).
Auxiliary state plus the answer structure where the problem requires one.