Alex Rivera | Logout

minimum difference between sum of two subsets

Asked 2010-11-18T05:54:06.987
11

Folks,

came across a problem... found this intersting... am modifying it a little bit just tu pep it up.

Given a set of integers (range 0-500), find the minimum difference between the sum of two subsets that can be formed by splitting them almost equally. (say count of integers is n, if n is even, each set must have n/2 elements and if n is odd, one set has (n-1)/2 elements and other has (n+1)/2 elements)

sample imput : 1 2 3 4 5 6

minimal difference = 1 (subsets being 1 4 6 and 2 3 5 )

sample input 2 : [ 1 1 1 1 2 2 2 2 ]

minimal difference = 0 (subsets being 1 1 2 2 and 1 1 2 2 )

is there DP approach for this problem.

Thanks guys...

raj...

Edit
Report

1 Answer

2

I've solved this problem recently using Dynamic Programming in c++. I have not modified the code to answer your question. But changing some constants and little code should do.

The code below reads and solves N problems.Each problem has some people (in your case number of integers) and their weights (integer values). This code tries to split the set into 2 groups with difference being minimum.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PEOPLE 100
#define MAX_WEIGHT 450
#define MAX_WEIGHT_SUM MAX_PEOPLE*MAX_WEIGHT
using namespace std;

int weights[MAX_PEOPLE];
//bool table[MAX_PEOPLE + 1][MAX_WEIGHT_SUM + 1]; 

bool** create2D(int x, int y) {
    bool **array = new bool*[x];
    for (int i = 0; i < x; ++i) {
        array[i] = new bool[y];
        memset(array[i], 0, sizeof(bool)*y);
    }
    return array;
}

void delete2D(int x, int y, bool **array) {
    for (int i = 0; i < x; ++i) {
        delete[] array[i];
    }
    delete[] array;
}

void memset2D(int x, int y, bool **array) {
    for(int i = 0; i < x; ++i)
        memset(array[i], 0, sizeof(bool)*y);
}

int main(void) {
    int n, N, W, maxDiff, teamWeight, temp;
    int minWeight = MAX_WEIGHT, maxWeight = -1;
    cin >> N;
    while(N--) {
        cin >> n;
        W = 0;
        for(int i = 0; i < n; ++i) {
            cin >> weights[i];
            if(weights[i] < minWeight)
                minWeight = weights[i];
            if(weights[i] > maxWeight)
                maxWeight = weights[i];

            W += weights[i];
        }
        int maxW = maxWeight + (W>>1);
        int maxn = n>>1;
        int index = 0;
    /* 
       table[j][i] = 1 if a team of j people can form i weight 
                        from K people, where k is implicit in loop
       table[j][i] = table[j-1][i-weight[j]] if i-weight[j] >=0
     */
        bool **table = create2D(max
answered 2010-11-21T09:48:09.683

Your Answer