Mid From PDF Coding C# Coding Interview

Number of ways to partition an array into subsets with equal sum?

public int CountPartitions(int[] nums) {
int sum = 0;
foreach (int num in nums) sum += num;
if (sum % 2 != 0) return 0;
int target = sum / 2;
int[] dp = new int[target + 1];
dp[0] = 1;

Follow on:

foreach (int num in nums) {
for (int j = target; j >= num; j--) {
dp[j] += dp[j - num];
}
}
return dp[target];
}

Explanation:

Classic subset sum DP. dp[j] = ways to get sum j. Counting subsets summing to half the

total.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details