File tree 1 file changed +8
-17
lines changed
scripts/algorithms/L/Largest Perimeter Triangle 1 file changed +8
-17
lines changed Original file line number Diff line number Diff line change 1
- // Runtime: 74 ms (Top 28.00%) | Memory: 21.8 MB (Top 71.53%)
2
1
class Solution {
3
2
public:
4
3
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
20
10
}
21
- return res;
11
+ return 0 ; // when no triangle possible it will come out of loop so return 0 here
12
+
22
13
}
23
14
};
You can’t perform that action at this time.
0 commit comments