Skip to content

Commit 5309dc7

Browse files
author
openset
committed
Add: Last Stone Weight
1 parent 9e52291 commit 5309dc7

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package last_stone_weight
2+
3+
import "sort"
4+
5+
func lastStoneWeight(stones []int) int {
6+
for len(stones) >= 2 {
7+
n := len(stones) - 1
8+
sort.Ints(stones)
9+
v := stones[n] - stones[n-1]
10+
if v > 0 {
11+
stones[n-1] = v
12+
} else {
13+
n--
14+
}
15+
stones = stones[:n]
16+
}
17+
stones = append(stones, 0)
18+
return stones[0]
19+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package last_stone_weight
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestLastStoneWeight(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{2, 7, 4, 1, 8, 1},
14+
expected: 1,
15+
},
16+
{
17+
input: []int{2, 7, 4, 1, 8, 1, 5},
18+
expected: 0,
19+
},
20+
{
21+
input: []int{316, 157, 73, 106, 771, 828},
22+
expected: 37,
23+
},
24+
}
25+
for _, tc := range tests {
26+
output := lastStoneWeight(tc.input)
27+
if output != tc.expected {
28+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)