From 9bb36d23d4a079411e43dc8696497f9dd5f3b466 Mon Sep 17 00:00:00 2001 From: ductnn Date: Thu, 15 Feb 2024 10:37:39 +0700 Subject: [PATCH] add sol --- .../findPolygonWiththeLargestPerimeter.go | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 leetcode/2971.FindPolygonWiththeLargestPerimeter/findPolygonWiththeLargestPerimeter.go diff --git a/leetcode/2971.FindPolygonWiththeLargestPerimeter/findPolygonWiththeLargestPerimeter.go b/leetcode/2971.FindPolygonWiththeLargestPerimeter/findPolygonWiththeLargestPerimeter.go new file mode 100644 index 0000000..6242e98 --- /dev/null +++ b/leetcode/2971.FindPolygonWiththeLargestPerimeter/findPolygonWiththeLargestPerimeter.go @@ -0,0 +1,40 @@ +// https://leetcode.com/problems/find-polygon-with-the-largest-perimeter + +package main + +import ( + "fmt" + "sort" +) + +func largestPerimeter(nums []int) int64 { + sort.Ints(nums) + n := len(nums) + s := make([]int, n+1) + + for i, v := range nums { + s[i+1] = s[i] + v + } + + res := -1 + for k := 3; k <= n; k++ { + if s[k-1] > nums[k-1] { + res = max(res, s[k]) + } + } + + return int64(res) +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func main() { + nums := []int{1, 12, 1, 2, 5, 50, 3} + + fmt.Println(largestPerimeter(nums)) +}