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

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

    I was asked this question in an interview, and I gave below simple solution, as I had NOT seen this problem in any websiteS earlier.

    Lets say Array A = {45,10,10,10,10,5} Then, the split will be at index = 1 (0-based index) so that we have two equal sum set {45} and {10,10,10,10,5}

    int leftSum = A[0], rightSum = A[A.length - 1];
    int currentLeftIndex = 0; currentRightIndex = A.length - 1
    

    /* Move the two index pointers towards mid of the array untill currentRightIndex != currentLeftIndex. Increase leftIndex if sum of left elements is still less than or equal to sum of elements in right of 'rightIndex'.At the end,check if leftSum == rightSum. If true, we got the index as currentLeftIndex+1(or simply currentRightIndex, as currentRightIndex will be equal to currentLeftIndex+1 in this case). */

    while (currentLeftIndex < currentRightIndex)
    {
    if ( currentLeftIndex+1 != currentRightIndex && (leftSum + A[currentLeftIndex + 1)     <=currentRightSum )
    {
     currentLeftIndex ++;
     leftSum = leftSum + A[currentLeftIndex];
    }
    
    
    if ( currentRightIndex - 1 != currentLeftIndex && (rightSum + A[currentRightIndex - 1] <= currentLeftSum)
    {
     currentRightIndex --;
     rightSum = rightSum + A[currentRightIndex];
    }
    
    }
    
    if (CurrentLeftIndex == currentRightIndex - 1 && leftSum == rightSum)
    PRINT("got split point at index "+currentRightIndex);
    

提交回复
热议问题