Skip to content

Commit 942ce4f

Browse files
committed
Array Addition 1
1 parent 961c1c8 commit 942ce4f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/easy/ArrayAdditionOne.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"sort"
6+
)
7+
8+
// ArrayAdditionOne checks if any combination of numbers in the array (excluding the largest number) can be added up to equal the largest number
9+
func ArrayAdditionOne(arr []int) string {
10+
// Find the largest number in the array
11+
sort.Ints(arr)
12+
largest := arr[len(arr)-1]
13+
14+
// Recursive function to find the sum of combinations
15+
var sumCombination func(int, int) bool
16+
sumCombination = func(target, index int) bool {
17+
// Base case: If target is 0, combination found
18+
if target == 0 {
19+
return true
20+
}
21+
// Base case: If index is out of range or target is negative, no combination found
22+
if index < 0 || target < 0 {
23+
return false
24+
}
25+
// Try including the current number in the sum
26+
include := sumCombination(target-arr[index], index-1)
27+
// Try excluding the current number from the sum
28+
exclude := sumCombination(target, index-1)
29+
// Return true if either including or excluding the current number results in a valid combination
30+
return include || exclude
31+
}
32+
33+
// Start exploring combinations, excluding the largest number
34+
return map[bool]string{true: "true", false: "false"}[sumCombination(largest, len(arr)-2)]
35+
}
36+
37+
func main() {
38+
result1 := ArrayAdditionOne([]int{4, 6, 23, 10, 1, 3})
39+
fmt.Println(result1)
40+
result2 := ArrayAdditionOne([]int{1,2,3, 5 ,7,8, 10})
41+
fmt.Println(result2)
42+
}

0 commit comments

Comments
 (0)