How to optimally divide an array into two subarrays so that sum of elements in both are same, otherwise give an error?

前端 未结 22 1070
一生所求
一生所求 2020-12-02 11:20

How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

22条回答
  •  囚心锁ツ
    2020-12-02 12:19

    Tried a different solution . other than Wiki solutions (Partition Problem).

    static void subSet(int array[]) {
        System.out.println("Input elements  :" + Arrays.toString(array));
    
        int sum = 0;
        for (int element : array) {
            sum = sum + element;
        }
        if (sum % 2 == 1) {
            System.out.println("Invalid Pair");
            return;
        }
    
        Arrays.sort(array);
        System.out.println("Sorted elements :" + Arrays.toString(array));
    
        int subSum = sum / 2;
    
        int[] subSet = new int[array.length];
        int tmpSum = 0;
        boolean isFastpath = true;
        int lastStopIndex = 0;
        for (int j = array.length - 1; j >= 0; j--) {
            tmpSum = tmpSum + array[j];
            if (tmpSum == subSum) { // if Match found
                if (isFastpath) { // if no skip required and straight forward
                                    // method
                    System.out.println("Found SubSets 0..." + (j - 1) + " and "
                            + j + "..." + (array.length - 1));
                } else {
                    subSet[j] = array[j];
                    array[j] = 0;
                    System.out.println("Found..");
                    System.out.println("Set 1" + Arrays.toString(subSet));
                    System.out.println("Set 2" + Arrays.toString(array));
                }
                return;
            } else {
                // Either the tmpSum greater than subSum or less .
                // if less , just look for next item
                if (tmpSum < subSum && ((subSum - tmpSum) >= array[0])) {
                    if (lastStopIndex > j && subSet[lastStopIndex] == 0) {
                        subSet[lastStopIndex] = array[lastStopIndex];
                        array[lastStopIndex] = 0;
                    }
                    lastStopIndex = j;
                    continue;
                }
                isFastpath = false;
                if (subSet[lastStopIndex] == 0) {
                    subSet[lastStopIndex] = array[lastStopIndex];
                    array[lastStopIndex] = 0;
                }
                tmpSum = tmpSum - array[j];
            }
        }
    
    }
    

    I have tested. ( It works well with positive number greater than 0) please let me know if any one face issue.

提交回复
热议问题