Skip to content

Commit cd4b790

Browse files
committed
Runtime 47 ms (Top 20.21%) | Memory 21.0 MB (Top 79.76%)
1 parent 8c1914f commit cd4b790

File tree

1 file changed

+8
-17
lines changed

1 file changed

+8
-17
lines changed
Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,14 @@
1-
// Runtime: 74 ms (Top 28.00%) | Memory: 21.8 MB (Top 71.53%)
21
class Solution {
32
public:
43
int largestPerimeter(vector<int>& nums) {
5-
int res = 0;
6-
7-
sort(nums.begin(),nums.end(),greater<int>());
8-
9-
for(int i = 0;i < nums.size()-2;i++)
10-
{
11-
int a = nums[i];
12-
int b = nums[i+1];
13-
int c = nums[i+2];
14-
15-
if(a<b+c&&b<a+c&&c<b+a)
16-
{
17-
res = res+a+b+c;
18-
break;
19-
}
4+
// sort the elements
5+
sort(nums.begin(),nums.end());
6+
// iterate in everse order to get maximum perimeter
7+
for (int i=nums.size()-2; i>=1 ; i--){
8+
//Triangle is formed if sum of two sides is greater than third side
9+
if (nums[i]+nums[i-1] >nums[i+1])return (nums[i]+nums[i+1]+nums[i-1]); // return perimeter which is sum of three sides
2010
}
21-
return res;
11+
return 0; // when no triangle possible it will come out of loop so return 0 here
12+
2213
}
2314
};

0 commit comments

Comments
 (0)