Skip to content

Commit 7bb0b89

Browse files
go: partition equal subset sum
1 parent 6dcfc26 commit 7bb0b89

File tree

1 file changed

+72
-0
lines changed
  • golang/algorithms/others/partition_equal_subset_sum

1 file changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package main
2+
3+
// Given an integer array nums, return true if
4+
// you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
5+
//
6+
// Example 1:
7+
//
8+
// Input: nums = [1,5,11,5]
9+
// Output: true
10+
// Explanation: The array can be partitioned as [1, 5, 5] and [11].
11+
// Example 2:
12+
//
13+
// Input: nums = [1,2,3,5]
14+
// Output: false
15+
// Explanation: The array cannot be partitioned into equal sum subsets.
16+
//
17+
// Constraints:
18+
//
19+
// 1 <= nums.length <= 200
20+
// 1 <= nums[i] <= 100
21+
22+
import (
23+
"maps"
24+
)
25+
26+
// time O(n)
27+
// space O(1)
28+
func sumSlice(nums []int) int {
29+
sum := 0
30+
for _, num := range nums {
31+
sum += num
32+
}
33+
return sum
34+
}
35+
36+
func canPartition(nums []int) bool {
37+
// O(n)
38+
sum := sumSlice(nums)
39+
// If the sum is odd it is impossible to divide it in 2.
40+
if sum&1 == 1 {
41+
return false
42+
}
43+
44+
half := sum / 2
45+
46+
seen := map[int]struct{}{
47+
0: {},
48+
}
49+
50+
// O(n)
51+
for _, num := range nums {
52+
newSeen := maps.Clone(seen)
53+
// O(sum(nums))
54+
for otherNum := range seen {
55+
total := num + otherNum
56+
if total == half {
57+
return true
58+
}
59+
if total < half {
60+
newSeen[total] = struct{}{}
61+
}
62+
63+
}
64+
seen = newSeen
65+
}
66+
67+
return false
68+
}
69+
70+
func main() {
71+
72+
}

0 commit comments

Comments
 (0)