Implement the canPartitionEqualSum method that checks whether the array can be split into two subsets with equal sum.

The input contains an integer array nums and its length size. Your task is to check whether the array can be divided into two subsets with equal sum.

If the total sum is odd, equal partition is impossible. If the total sum is even, the problem becomes checking whether any subset can make half of the total sum. For example, [1,5,11,5] can be split into [11] and [1,5,5], so the answer is true.

Example 1

Input
nums (int[]) = [1,5,11,5]
size (int) = 4
Returns (boolean) true

Example 2

Input
nums (int[]) = [1,2,3,5]
size (int) = 4
Returns (boolean) false

Example 3

Input
nums (int[]) = [2,2,3,5]
size (int) = 4
Returns (boolean) false

First calculate the total sum of the array. If it is odd, return false immediately.

Otherwise, set target = total / 2. Now check whether there is a subset whose sum is equal to this target.

Use a boolean dynamic programming array. dp[x] tells whether sum x can be formed using the numbers processed so far. Loop backward for each number so that each array value is used only once.

Pseudocode:

function canPartitionEqualSum(nums, size):
    total = sum of all values in nums
    if total % 2 != 0:
        return false
    target = total / 2
    dp = boolean array of target + 1 values filled with false
    dp[0] = true
    for each num in nums:
        for sumValue from target down to num:
            dp[sumValue] = dp[sumValue] or dp[sumValue - num]
    return dp[target]
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.