parent
b8c2a2e5cd
commit
f27ce6893e
@ -0,0 +1,27 @@
|
||||
package largestperimeter
|
||||
|
||||
import (
|
||||
"sort"
|
||||
)
|
||||
|
||||
func isTriangle(a, b, c int) bool {
|
||||
return a < b+c
|
||||
}
|
||||
|
||||
func largestPerimeter(nums []int) int {
|
||||
|
||||
sort.Ints(nums)
|
||||
|
||||
for i := len(nums) - 1; i >= 2; i-- {
|
||||
a, b, c := nums[i], nums[i-1], nums[i-2]
|
||||
if isTriangle(a, b, c) {
|
||||
return a + b + c
|
||||
}
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func Triangle(nums []int) int {
|
||||
return largestPerimeter(nums)
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package largestperimeter_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.jxs.me/leetgo/largestperimeter"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestEmpty(t *testing.T) {
|
||||
require.Equal(t, 0, largestperimeter.Triangle([]int{}))
|
||||
}
|
||||
|
||||
func TestTooSmall(t *testing.T) {
|
||||
require.Equal(t, 0, largestperimeter.Triangle([]int{1, 2}))
|
||||
}
|
||||
|
||||
func TestWorking(t *testing.T) {
|
||||
require.Equal(t, 5, largestperimeter.Triangle([]int{2, 1, 2}))
|
||||
}
|
||||
|
||||
func TestInvalid(t *testing.T) {
|
||||
require.Equal(t, 0, largestperimeter.Triangle([]int{2, 1, 1}))
|
||||
}
|
||||
|
||||
func TestHundredSize(t *testing.T) {
|
||||
require.Equal(t, 118, largestperimeter.Triangle([]int{100, 49, 50, 7, 19}))
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
976. Largest Perimeter Triangle
|
||||
Easy
|
||||
|
||||
Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: nums = [2,1,2]
|
||||
Output: 5
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: nums = [1,2,1]
|
||||
Output: 0
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
3 <= nums.length <= 104
|
||||
1 <= nums[i] <= 106
|
Loading…
Reference in new issue