MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / PartitionProblem

Function PartitionProblem

dynamic/partitionproblem.go:11–30  ·  view source on GitHub ↗

PartitionProblem checks whether the given set can be partitioned into two subsets such that the sum of the elements in both subsets is the same.

(nums []int)

Source from the content-addressed store, hash-verified

9// PartitionProblem checks whether the given set can be partitioned into two subsets
10// such that the sum of the elements in both subsets is the same.
11func PartitionProblem(nums []int) bool {
12 sum := 0
13 for _, num := range nums {
14 sum += num
15 }
16 if sum%2 != 0 {
17 return false
18 }
19
20 target := sum / 2
21 dp := make([]bool, target+1)
22 dp[0] = true
23
24 for _, num := range nums {
25 for i := target; i >= num; i-- {
26 dp[i] = dp[i] || dp[i-num]
27 }
28 }
29 return dp[target]
30}

Callers 1

TestPartitionProblemFunction · 0.92

Calls

no outgoing calls

Tested by 1

TestPartitionProblemFunction · 0.74