From 898040fcad3eb236fd2c02520ca66948e7b5182c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 16 Jun 2024 11:46:41 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB330.=20Patching=20Array=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/patching-array.go | 19 +++++++++++++++++++ go/patching-array_test.go | 22 ++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 go/patching-array.go create mode 100644 go/patching-array_test.go diff --git a/go/patching-array.go b/go/patching-array.go new file mode 100644 index 0000000..282476d --- /dev/null +++ b/go/patching-array.go @@ -0,0 +1,19 @@ +package main + +func minPatches(nums []int, n int) int { + missing := 1 + patches := 0 + + i := 0 + for missing <= n { + if i < len(nums) && nums[i] <= missing { + missing += nums[i] + i++ + } else { + missing += missing + patches++ + } + } + + return patches +} diff --git a/go/patching-array_test.go b/go/patching-array_test.go new file mode 100644 index 0000000..0dbf182 --- /dev/null +++ b/go/patching-array_test.go @@ -0,0 +1,22 @@ +package main + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_PatchingArray_Example1(t *testing.T) { + assert := assert.New(t) + assert.Equal(1, minPatches([]int{1, 3}, 6)) +} + +func Test_PatchingArray_Example2(t *testing.T) { + assert := assert.New(t) + assert.Equal(2, minPatches([]int{1, 5, 10}, 20)) +} + +func Test_PatchingArray_Example3(t *testing.T) { + assert := assert.New(t) + assert.Equal(0, minPatches([]int{1, 2, 2}, 5)) +}