diff --git a/problems/array-partition-i/array_partition_i.go b/problems/array-partition-i/array_partition_i.go index 84f23947e..de5fcaa78 100644 --- a/problems/array-partition-i/array_partition_i.go +++ b/problems/array-partition-i/array_partition_i.go @@ -1 +1,14 @@ package array_partition_i + +import "sort" + +func arrayPairSum(nums []int) int { + sum := 0 + sort.Ints(nums) + for i, v := range nums { + if i&1 == 0 { + sum += v + } + } + return sum +} diff --git a/problems/array-partition-i/array_partition_i_test.go b/problems/array-partition-i/array_partition_i_test.go index 84f23947e..6dd5b22c2 100644 --- a/problems/array-partition-i/array_partition_i_test.go +++ b/problems/array-partition-i/array_partition_i_test.go @@ -1 +1,23 @@ package array_partition_i + +import "testing" + +type caseType struct { + input []int + expected int +} + +func TestArrayPairSum(t *testing.T) { + tests := [...]caseType{ + { + input: []int{1, 4, 3, 2}, + expected: 4, + }, + } + for _, tc := range tests { + output := arrayPairSum(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}