Skip to content
Related Articles

Related Articles

Maximum possible difference between two Subarrays after removing N elements from Array

View Discussion
Improve Article
Save Article
  • Last Updated : 01 Sep, 2022
View Discussion
Improve Article
Save Article

Given an array arr[] which is of 3*N size, the task is to remove N elements and divide the whole array into two equal parts such that the  difference of the sum of the left subarray and right subarray should yield to maximum.


Input: arr[] = [5, 4, 4, 2, 3, 3]
Output: 4
Explanation:  The ‘2’ elements to be removed are [4, 3]. 
and when you divide the array into two equal parts after the removal
left subarray= [5, 4], right subarray= [2, 3]. 
The Sum difference between them is (9-5) = 4

Input: arr[] = [4, 5, 6, 1, 2, 8, 7, 9, 3]
Output: 9


Split the array into two subarrays at some point i (N <= i <= 2 * N). We remove i – N smallest elements from the first subarray, and (2 * N – i) largest elements from the second subarray. That way, for a given split, we get the largest possible sum_first, and smallest possible sum_second.

Using Max and Min heap to keep track of the smallest and largest elements, respectively. And update the difference.

Follow the below steps to Implement the Idea:

  • Initialize a final_diff variable to store the maximum difference between left and right subarray after removal of N elements.
  • Run a for loop from N to 2*N and arr[] into two halves left and right.
    • Remove i – N smallest elements from left array and 2*N – i largest elements from right array by using Min and Max heap.
    • Calculate the sum of N largest values in left array and N smallest values in right array and find out the difference between them and store it in Curr_diff variable.
    • Maximize the value of final_diff with curr_diff
  • Return the value of final_diff.

Below is the implementation


import copy
import heapq
from collections import Counter
# This function return the (1, n-1) min and max
# elements which are t be discarded from the array
def best_remove(left, right):
    temp = []
    if len(left) == n and len(right) > n:
        # remove all n elements from the right side
        temp.extend(heapq.nlargest(n, right))
    elif len(right) == n and len(left) > n:
        # remove all element from the left side
        temp.extend(heapq.nsmallest(n, left))
        x = len(left) - n
        temp.extend(heapq.nsmallest(x, left)+heapq.nlargest(n-x, right))
    return temp
def remove_elements(parent, child):
    f_s = Counter(child)
    # storing all the elements of right
    # part to preserve the order incase of duplicates
    r_h = [] 
    for i in parent:
        if i in f_s and f_s[i] > 0:
            f_s[i] -= 1
    # print("after r", left + r_h)
    return r_h
    # Remove the child from parent
    # divide the array
    # sum the left and right elements
    # track the curr max sum until the for loops terminates
    # return the final max difference
    # print(parent, n, child, m)
    # print(left, right)
def max_diff(arr):  # function that calculate the sum of maximum difference between two arrays
    # print(arr)
    mid = len(arr)//2
    left = sum(arr[:mid])
    right = sum(arr[mid:])
    return left-right
arr = [7, 9, 5, 8, 1, 3]
n = len(arr)//3
final_max = -float("inf")
# starting from the index 2
for i in range(n, 2 * n + 1):
    left = arr[:i]  # dividing the left
    right = arr[i:]  # dividing the right sub array
    # print(left, right)
    # functions which returns the best elements to be removed from both sub arrays
    best_remove_elements = best_remove(left, right)
    # print(best_remove_elements)
    dup = []
    # copying the original array so that the changes might not reflect
    dup = copy.deepcopy(arr)
    # function that returns the array after removing the best_remove elements
    remove_element = remove_elements(dup, best_remove_elements)
    # print(remove_element)
    # return(remove_element)
    curr_max = max_diff(remove_element)  # tracking the maximum
    final_max = max(final_max, curr_max)
print("The maximum difference between S1 and S2 is", final_max)

The maximum difference between S1 and S2 is 13

Time Complexity: (N*log(N))
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!