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

前端 未结 22 1068
一生所求
一生所求 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 11:57

    Algorithm:

    Step 1) Split the array into two
    Step 2) If the sum is equal, split is complete
    Step 3) Swap one element from array1 with array2, guided by the four rules:
       IF the sum of elements in array1 is less than sum of elements in array2
          Rule1:
             Find a number in array1 that is smaller than a number in array2 in such a way that swapping of          these elements, do not increase the sum of array1 beyond the expected sum. If found, swap the          elements and return.
          Rule2:
             If Rule1 is not is not satisfied, Find a number in array1 that is bigger than a number in array2 in          such a way that the difference between any two numbers in array1 and array2 is not smaller than          the difference between these two numbers.
       ELSE
          Rule3:
             Find a number in array1 that is bigger than a number in array2 in such a way that swapping these          elements, do not decrease the sum of array1 beyond the expected sum. If found, swap the
             elements and return.
          Rule4:
             If Rule3 is not is not satisfied, Find a number in array1 that is smaller than a number in array2 in          such a way that the difference between any two numbers in array1 and array2 is not smaller than          the difference between these two numbers.
    Step 5) Go to Step2 until the swap results in an array with the same set of elements encountered already Setp 6) If a repetition occurs, this array cannot be split into two halves with equal sum. The current set of           arrays OR the set that was formed just before this repetition should be the best split of the array.

    Note: The approach taken is to swap element from one array to another in such a way that the resultant sum is as close to the expected sum.

    The java program is available at Java Code

提交回复
热议问题