Блог пользователя priyesh001

Автор priyesh001, 9 лет назад, По-английски

Given an array S of N positive integers, divide the array into two subsets such that the sums of subsets is maximum and equal. It is not necessary to include all the elements in the two subsets. Same element should not appear in both the subsets. The output of the program should be the maximum possible sum.

Constraints:
1 <= N <= 50
1 <= S[i] <= 1000
Sum of elements of S will not be greater than 1000.
Example:
Input:
5
2 3 4 1 6
Output:
8 {Explanation: The two subsets with maximum sum are [1,3,4] and [2,6]}

I found this question in one of the interview challenge. I used the traditional sum of subsets logic to find all the possible sum for n elements and then tried to reconstruct non-overlapping subsets for a sum from the 2D DP array. I couldn't get all tc to pass. Is there any better easier solution for this?

  • Проголосовать: нравится
  • -1
  • Проголосовать: не нравится

»
9 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Can you provide the link for that problem?

»
9 лет назад, скрыть # |
Rev. 5  
Проголосовать: нравится 0 Проголосовать: не нравится

I think this problem can be solved in O(N·totalsum2). Iterate over all possible sums and count the number of non-overlapping subsets with that sum. If the number of subsets is greater than or equal to 2 then you can divide the array into two subsets with sum equal to the current sum. You can count the number of non-overlapping subsets with sum equal to K in O(NK) using DP. This can be done with a slight modification to the standard 'count subsets with given sum' DP problem.

To see how to do it check here.

»
9 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Hint: try to find all pairs (x, y) such that you can find two non-intersecting subsets with sums x and y. It's very similar to all possible sums of subsets.

»
9 лет назад, скрыть # |
 
Проголосовать: нравится +22 Проголосовать: не нравится

O(N·totalsum) solution. Let's count dp[n][diff] — maximum such X, that in elements S[1], ... S[n] there are two non-intersecting subsets with sums X and X + diff. Calculation is simple, n'th element can either be in the first subset, in second or not used at all. And problem's answer is dp[N][0]

»
6 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

For anyone who wants to test their code: URI 1700

»
6 лет назад, скрыть # |
 
Проголосовать: нравится +1 Проголосовать: не нравится

This problem can also be tested here https://leetcode.com/problems/tallest-billboard/