Skip to content

Commit 8ec751a

Browse files
committed
2971. Find Polygon With the Largest Perimeter
1 parent 51ffdc1 commit 8ec751a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
3+
// Solution by Sergey Leschev
4+
// 2971. Find Polygon With the Largest Perimeter
5+
6+
// Time complexity: O(n)
7+
// Space complexity: O(1)
8+
9+
func largestPerimeter(_ nums: [Int]) -> Int {
10+
var sortedNums = nums.sorted(by: <)
11+
var sum = 0
12+
13+
for num in sortedNums {
14+
sum += num
15+
}
16+
17+
for i in stride(from: sortedNums.count - 1, through: 2, by: -1) {
18+
sum -= sortedNums[i]
19+
if sortedNums[i] < sum {
20+
return sum + sortedNums[i]
21+
}
22+
}
23+
24+
return -1
25+
}
26+
}

0 commit comments

Comments
 (0)