From 21e95a3c3172396f23617a52d7016e62acf0d323 Mon Sep 17 00:00:00 2001 From: Kei Kamikawa Date: Tue, 14 Apr 2020 21:53:25 +0900 Subject: [PATCH] added last stone weight solution --- last-stone-weight/solution.go | 26 ++++++++++++++++++++++++ last-stone-weight/solution_test.go | 32 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 last-stone-weight/solution.go create mode 100644 last-stone-weight/solution_test.go diff --git a/last-stone-weight/solution.go b/last-stone-weight/solution.go new file mode 100644 index 0000000..de09874 --- /dev/null +++ b/last-stone-weight/solution.go @@ -0,0 +1,26 @@ +package solution + +import "sort" + +// Last Stone Weight +// https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3297/ + +// Note: +// +// 1 <= stones.length <= 30 +// 1 <= stones[i] <= 1000 +func lastStoneWeight(stones []int) int { + for { + sort.Ints(stones) + ln := len(stones) + switch ln { + case 0: + return 0 + case 1: + return stones[0] + } + + diff := stones[ln-1] - stones[ln-2] + stones = append(stones[:ln-2], diff) + } +} diff --git a/last-stone-weight/solution_test.go b/last-stone-weight/solution_test.go new file mode 100644 index 0000000..be67ce2 --- /dev/null +++ b/last-stone-weight/solution_test.go @@ -0,0 +1,32 @@ +package solution + +import ( + "fmt" + "testing" +) + +func Test_lastStoneWeight(t *testing.T) { + type args struct { + } + tests := []struct { + stones []int + want int + }{ + { + stones: []int{2, 7, 4, 1, 8, 1}, + want: 1, + }, + { + stones: []int{2, 7, 4, 1, 8, 1, 3, 4, 100, 304, 1000}, + want: 566, + }, + } + for i, tt := range tests { + title := fmt.Sprintf("testcase: %d", i+1) + t.Run(title, func(t *testing.T) { + if got := lastStoneWeight(tt.stones); got != tt.want { + t.Errorf("lastStoneWeight() = %v, want %v", got, tt.want) + } + }) + } +}