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

前端 未结 22 982
一生所求
一生所求 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:03

    Please try this and let me know if not working. Hope it will helps you.

    static ArrayList array = null;
    
    public static void main(String[] args) throws IOException {
    
        ArrayList inputArray = getinputArray();
        System.out.println("inputArray is " + inputArray);
        Collections.sort(inputArray);
    
        int totalSum = 0;
    
        Iterator inputArrayIterator = inputArray.iterator();
        while (inputArrayIterator.hasNext()) {
            totalSum = totalSum + inputArrayIterator.next();
        }
        if (totalSum % 2 != 0) {
            System.out.println("Not Possible");
            return;
        }
    
        int leftSum = inputArray.get(0);
        int rightSum = inputArray.get(inputArray.size() - 1);
    
        int currentLeftIndex = 0;
        int currentRightIndex = inputArray.size() - 1;
    
        while (leftSum <= (totalSum / 2)) {
            if ((currentLeftIndex + 1 != currentRightIndex)
                    && leftSum != (totalSum / 2)) {
                currentLeftIndex++;
                leftSum = leftSum + inputArray.get(currentLeftIndex);
            } else
                break;
    
        }
        if (leftSum == (totalSum / 2)) {
            ArrayList splitleft = new ArrayList();
            ArrayList splitright = new ArrayList();
    
            for (int i = 0; i <= currentLeftIndex; i++) {
                splitleft.add(inputArray.get(i));
            }
            for (int i = currentLeftIndex + 1; i < inputArray.size(); i++) {
                splitright.add(inputArray.get(i));
            }
            System.out.println("splitleft is :" + splitleft);
            System.out.println("splitright is :" + splitright);
    
        }
    
        else
            System.out.println("Not possible");
    }
    
    public static ArrayList getinputArray() {
        Scanner scanner = new Scanner(System.in);
        array = new ArrayList();
        int size;
        System.out.println("Enter the Initial array size : ");
        size = scanner.nextInt();
        System.out.println("Enter elements in the array");
        for (int j = 0; j < size; j++) {
            int element;
            element = scanner.nextInt();
            array.add(element);
        }
        return array;
    }
    

    }

提交回复
热议问题