 Open in App
Not now

# Minimize difference between maximum and minimum Subarray sum by splitting Array into 4 parts

• Difficulty Level : Hard
• Last Updated : 19 May, 2022

Given an array arr[] of size N, the task is to find the minimum difference between the maximum and the minimum subarray sum when the given array is divided into 4 non-empty subarrays.

Examples:

Input: N = 5, arr[] = {3, 2, 4, 1, 2}
Output: 2
Explanation: Divide the array into four parts as {3}, {2}, {4} and {1, 2}
The sum of all the elements of these parts is 3, 2, 4, and 3
The difference between the maximum and minimum is (4 – 2) = 2.

Input: N = 4, arr[] = {14, 6, 1, 7}
Output: 13
Explanation:  Divide the array into four parts {14}, {6}, {1} and {7}
The sum of all the elements of these four parts is 14, 6, 1, and 7
The difference between the maximum and minimum (14 – 1) = 13.
It is the only possible way to divide the array into 4 possible parts

Naive Approach: The simplest way is to check for all possible combinations of three cuts and for each possible value check the subarray sums. Then calculate the minimum difference among all the possible combinations.

Time Complexity: O(N4)
Auxiliary Space: O(1)

Efficient Approach: The problem can be solved using the concept of prefix sum and two-pointer based on the below observation:

To divide the array into 4 subarrays three splits are required.

• If the second split is fixed (say in between index i and i+1) there will be one split to the left and one split to the right.
• The difference will be minimized when the two subarrays on left will have sum as close to each other as possible and same for the two subarrays on the right side of the split.
• The overall sum of the left part and of the right part can be obtained  in constant time with the help of prefix sum calculation.

Now the split on the left part and on the right part can be decided optimally using the two-pointer technique.

• When the second split is fixed decide the left split by iterating through the left part till the difference between the sum of two parts is minimum.
• It can be found by minimizing the difference between the overall sum and twice the sum of any of the part. [The minimum value of this signifies that the difference between both the parts is minimum]

Do the same for the right part also.

Follow the below steps to solve this problem:

• Firstly pre-compute the prefix sum array of the given array.
• Create three variables i = 1, j = 2, and k = 3 each representing the cuts.(1 based indexing)
• Iterate through possible values of j from 2 to N – 1.
• For each value of j try to increase the value of i until the absolute difference between the Left_Sum_1 and Left_Sum_2 decreases and i is less than j (Left_Sum_1 and Left_Sum_2 are the sums of the two subarrays on the left).
• For each value of j, try to increase the value of k, until the absolute difference between the Right_Sum_1 and Right_Sum_2 decreases and k is less than N + 1 (Right_Sum_1 and Right_Sum_2 are the sums of the two subarrays of the right).
• Use prefix sum to directly calculate the values of Left_Sum_1, Left_Sum_2, Right_Sum_1 and Right_Sum_2.
• For each valid value of i, j and k, find the difference between the maximum and minimum value of the sum of elements of these parts
• The minimum among them is the answer.

Below is the implementation of the above approach:

## C++

 `// C++ code to implement the approach`   `#include ` `using` `namespace` `std;`   `// Function to find the minimum difference` `// between maximum and minimum subarray sum` `// after dividing the array into 4 subarrays` `long` `long` `int` `minSum(vector<``int``>& v, ``int` `n)` `{` `    ``vector<``long` `long` `int``> a(n + 1);`   `    ``// Precompute the prefix sum` `    ``a = 0;` `    ``for` `(``int` `i = 1; i <= n; i++) {` `        ``a[i] = a[i - 1] + v[i - 1];` `    ``}`   `    ``// Initialize the ans with large value` `    ``long` `long` `int` `ans = 1e18;`   `    ``// There are total four parts means 3 cuts.` `    ``// Here i, j, k represent those 3 cuts` `    ``for` `(``int` `i = 1, j = 2, k = 3; j < n; j++) {` `        ``while` `(i + 1 < j` `               ``&& ``abs``(a[j] - 2 * a[i])` `                      ``> ``abs``(a[j]` `                            ``- 2 * a[i + 1])) {` `            ``i++;` `        ``}` `        ``while` `(k + 1 < n` `               ``&& ``abs``(a[n] + a[j] - 2 * a[k])` `                      ``> ``abs``(a[n] + a[j]` `                            ``- 2 * a[k + 1])) {` `            ``k++;` `        ``}` `        ``ans = min(ans,` `                  ``max({ a[i], a[j] - a[i],` `                        ``a[k] - a[j],` `                        ``a[n] - a[k] })` `                      ``- min({ a[i], a[j] - a[i],` `                              ``a[k] - a[j],` `                              ``a[n] - a[k] }));` `    ``}` `    ``return` `ans;` `}`   `// Driver Code` `int` `main()` `{` `    ``vector<``int``> arr = { 3, 2, 4, 1, 2 };` `    ``int` `N = arr.size();`   `    ``// Function call` `    ``cout << minSum(arr, N);` `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `public` `class` `GFG ` `{`   `  ``// Function to find the minimum difference` `  ``// between maximum and minimum subarray sum` `  ``// after dividing the array into 4 subarrays` `  ``static` `int` `minCost(``int` `arr[], ``int` `n)` `  ``{`   `    ``// Precompute the prefix sum` `    ``int` `a[] = ``new` `int``[n + ``1``];` `    ``a[``0``] = ``0``;` `    ``for` `(``int` `i = ``1``; i <= n; i++) {` `      ``a[i] = a[i - ``1``] + arr[i - ``1``];` `    ``}`   `    ``// Initialize the ans with large value` `    ``int` `ans = Integer.MAX_VALUE;`   `    ``// There are total four parts means 3 cuts.` `    ``// Here i, j, k represent those 3 cuts` `    ``for` `(``int` `i = ``1``, j = ``2``, k = ``3``; j < n; j++) {` `      ``while` `(i + ``1` `< j` `             ``&& Math.abs(a[j] - ``2` `* a[i])` `             ``> Math.abs(a[j] - ``2` `* a[i + ``1``])) {` `        ``i++;` `      ``}` `      ``while` `(k + ``1` `< n` `             ``&& Math.abs(a[n] + a[j] - ``2` `* a[k])` `             ``> Math.abs(a[n] + a[j]` `                        ``- ``2` `* a[k + ``1``])) {` `        ``k++;` `      ``}` `      ``ans = Math.min(` `        ``ans,` `        ``Math.max(a[i],` `                 ``Math.max(a[j] - a[i],` `                          ``Math.max(a[k] - a[j],` `                                   ``a[n] - a[k])))` `        ``- Math.min(` `          ``a[i],` `          ``Math.min(a[j] - a[i],` `                   ``Math.min(a[k] - a[j],` `                            ``a[n] - a[k]))));` `    ``}` `    ``return` `ans;` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `main(String[] args)` `  ``{`   `    ``int` `arr[] = { ``3``, ``2``, ``4``, ``1``, ``2` `};` `    ``int` `N = arr.length;`   `    ``System.out.println(minCost(arr, N));` `  ``}` `}`   `// This code is contributed by dwivediyash`

## Python3

 `# Python3 code to implement the approach`   `# Function to find the minimum difference` `# between maximum and minimum subarray sum` `# after dividing the array into 4 subarrays` `def` `minSum(v, n):` `    ``a ``=` `[``0``]`   `    ``# Precompute the prefix sum` `    ``for` `i ``in` `range``(``1``, n ``+` `1``):` `        ``a.append(a[``-``1``] ``+` `v[i ``-` `1``])`   `    ``# Initialize the ans with large value` `    ``ans ``=` `10` `*``*` `18`   `    ``# There are total four parts means 3 cuts.` `    ``# Here i, j, k represent those 3 cuts` `    ``i ``=` `1` `    ``j ``=` `2` `    ``k ``=` `3` `    ``while` `(j < n):` `        ``while` `(i ``+` `1` `< j ``and` `abs``(a[j] ``-` `2` `*` `a[i]) > ``abs``(a[j] ``-` `2` `*` `a[i ``+` `1``])):` `            ``i ``+``=` `1` `        ``while` `(k ``+` `1` `< n ``and` `abs``(a[n] ``+` `a[j] ``-` `2` `*` `a[k]) > ``abs``(a[n] ``+` `a[j] ``-` `2` `*` `a[k ``+` `1``])):` `            ``k ``+``=` `1` `        ``ans ``=` `min``(ans, ``max``([a[i], a[j] ``-` `a[i], a[k] ``-` `a[j], a[n] ``-` `a[k]]` `                           ``) ``-` `min``([a[i], a[j] ``-` `a[i], a[k] ``-` `a[j], a[n] ``-` `a[k]]))` `        ``j ``+``=` `1`   `    ``return` `ans`   `# Driver Code` `arr ``=` `[``3``, ``2``, ``4``, ``1``, ``2``]` `N ``=` `len``(arr)`   `# Function call` `print``(minSum(arr, N))`   `# this code is contributed by phasing17`

## C#

 `// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG` `{`   `// Function to find the minimum difference` `// between maximum and minimum subarray sum` `// after dividing the array into 4 subarrays` `static` `int` `minCost(``int``[] arr, ``int` `n)` `{`   `    ``// Precompute the prefix sum` `    ``int``[] a = ``new` `int``[n + 1];` `    ``a = 0;` `    ``for` `(``int` `i = 1; i <= n; i++) {` `    ``a[i] = a[i - 1] + arr[i - 1];` `    ``}`   `    ``// Initialize the ans with large value` `    ``int` `ans = Int16.MaxValue;`   `    ``// There are total four parts means 3 cuts.` `    ``// Here i, j, k represent those 3 cuts` `    ``for` `(``int` `i = 1, j = 2, k = 3; j < n; j++) {` `    ``while` `(i + 1 < j` `            ``&& Math.Abs(a[j] - 2 * a[i])` `            ``> Math.Abs(a[j] - 2 * a[i + 1])) {` `        ``i++;` `    ``}` `    ``while` `(k + 1 < n` `            ``&& Math.Abs(a[n] + a[j] - 2 * a[k])` `            ``> Math.Abs(a[n] + a[j]` `                        ``- 2 * a[k + 1])) {` `        ``k++;` `    ``}` `    ``ans = Math.Min(` `        ``ans,` `        ``Math.Max(a[i],` `                ``Math.Max(a[j] - a[i],` `                        ``Math.Max(a[k] - a[j],` `                                ``a[n] - a[k])))` `        ``- Math.Min(` `        ``a[i],` `        ``Math.Min(a[j] - a[i],` `                ``Math.Min(a[k] - a[j],` `                            ``a[n] - a[k]))));` `    ``}` `    ``return` `ans;` `}`   `// Driver Code` `public` `static` `void` `Main(String[] args)` `{` `    ``int``[] arr = { 3, 2, 4, 1, 2 };` `    ``int` `N = arr.Length;` `    `  `    ``// Function call` `    ``Console.WriteLine(minCost(arr, N));` `}` `}`   `// This code is contributed by Pushpesh Raj`

## Javascript

 ``

Output

`2`

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

My Personal Notes arrow_drop_up
Related Articles