CN: Difference of subset sums is minimum

Problem

Intuition

In this problem, we need to find out what is the minimum difference between subset sums. All the numbers given are non-negative integers.

It is more like a modified extension of 416. Partition Equal Subset Sum problem.

Here there is no target to be searched. As we ought to find the minimum subset sum difference, we take totalSum and find the partition for totalSum.

The core logic of finding the target subset is same.

Once we fill in the DP table for finding the totalSum then we take the last row of DP and figure out what is the minimum difference between current sum and complement of it. We keep a track of the minimum difference.

Here every number in last row of DP represents a sum. So to find minimum difference we need to take another subset sum, that can be found by totalSum-currenSubsetSum , keeping track of minimum of the difference is the solution.

Time Complexity

n -> Number of elements in input array

O(n*totalSum) --> Number of loops

O(n) --> Finding totalSum

O(n) --> Finding the minimum subset sum difference

Space Complexity

n -> Number of elements in input array

It is space optimised approach

Solution

Last updated