Drop two elements to split the array to three part evenly in O(n)

前端 未结 3 2032
迷失自我
迷失自我 2021-02-07 19:07

I encounter a problem to let you drop two elements in an array to make the three part\'s sum equal.

  Ex:
  1 2 4 3 5 2 1
  After I drop the 4 and 5, it becomes          


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-07 19:47

    • Step 1: Create a sum array

    • Step 2: Follow two pointer approach

        public boolean solution(int[] A) {
      
        int leftPointer = 1;
        int rightPointer = A.length - 2;
        int leftPartSum, middlePartSum, rightPartSum;
        int[] sumArray = new int[A.length];
      
        // Initializing the sum array
        sumArray[0] = A[0];
        for(int i = 1; i < A.length; i ++)
            sumArray[i] = sumArray[i-1] +  A[i];
      
        // Using two Pointer technique
        while(leftPointer < rightPointer) {
      
            leftPartSum = sumArray[leftPointer] - A[leftPointer];
            middlePartSum = sumArray[rightPointer] - sumArray[leftPointer] - A[rightPointer];
            rightPartSum = sumArray[A.length - 1] - sumArray[rightPointer];
      
            if(leftPartSum == middlePartSum && middlePartSum == rightPartSum)
                return true;
      
            if (leftPartSum < rightPartSum)
                leftPointer++;
            else if (leftPartSum > rightPartSum)
                rightPointer--;
            else{                   // Else condition denotes: leftPartSum == rightPartSum
                leftPointer++;
                rightPointer--;
            }
        }
        return false; // If no solution is found then returning false
        }
      

    Detailed Explanation:

    Sum Array: In the first pass over array, count the accumulated sum from the left to right. Althought this will take O(n) time to create a sum array but this will help you in getting the leftPartSum, middlePartSum and rightPartSum in O(1) at any given time.

    Two Pointer Approach: In two pointer approach, One pointer starts from the beginning while the other pointer starts from the end.

    In this case, If we remove the first element or last element, then there is no way in which we can split the array into 3 equal parts. Hence, we can safely assume that

    int leftPointer = 1; 
    int rightPointer = A.length - 2;
    

    Note: Array contains indexed from 0 to n-1;

    Now, we move the pointer towards each other and at every movement we calculate leftPartSum, middlePartSum and rightPartSum. Whether we need to move left pointer or right pointer is decided by the fact that which one of the two sums (leftPartSum or rightPartSum is smaller)

提交回复
热议问题