Largest Perimeter Triangle Solutions in C++
Number 976
Difficulty Easy
Acceptance 57.7%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
class Solution {public:int largestPerimeter(vector<int>& A) {if (A.size() < 3) return 0;sort(A.begin(), A.end(), greater<int>());for (auto it = A.begin(); it != A.end() - 2; ++it) {if (*it < *(it + 1) + *(it + 2))return *it + *(it + 1) + *(it + 2);}return 0;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/largest-perimeter-triangle//// Author : liuyubobobo/// Time : 2019-01-12#include <iostream>#include <vector>#include <algorithm>using namespace std;/// Sort and Brute Force/// Time Complexity: O(n^2)/// Space Complexity: O(1)class Solution {public:int largestPerimeter(vector<int>& A) {sort(A.begin(), A.end());int n = A.size();int best = 0;for(int i = n - 1; i >= 0; i --)for(int j = i - 1; j >= 0; j --){if(j - 1 >= 0 && A[j - 1] > A[i] - A[j])best = max(best, A[i] + A[j] + A[j - 1]);elsebreak;}return best;}};int main() {vector<int> A1 = {2, 3, 3, 4};cout << Solution().largestPerimeter(A1) << endl;// 10vector<int> A2 = {2, 3, 3, 6};cout << Solution().largestPerimeter(A2) << endl;// 8return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/largest-perimeter-triangle//// Author : liuyubobobo/// Time : 2019-01-21#include <iostream>#include <vector>#include <algorithm>using namespace std;/// Sort and Greedy/// Time Complexity: O(nlogn)/// Space Complexity: O(1)class Solution {public:int largestPerimeter(vector<int>& A) {sort(A.begin(), A.end());for(int i = A.size() - 3; i >= 0; i --)if(A[i] + A[i + 1] > A[i + 2])return A[i] + A[i + 1] + A[i + 2];return 0;}};int main() {vector<int> A1 = {2, 3, 3, 4};cout << Solution().largestPerimeter(A1) << endl;// 10vector<int> A2 = {2, 3, 3, 6};cout << Solution().largestPerimeter(A2) << endl;// 8return 0;}