Minimize difference between maximum and minimum Subarray sum by splitting Array into 4 parts
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++
#include <bits/stdc++.h>
using namespace std;
long long int minSum(vector< int >& v, int n)
{
vector< long long int > a(n + 1);
a[0] = 0;
for ( int i = 1; i <= n; i++) {
a[i] = a[i - 1] + v[i - 1];
}
long long int ans = 1e18;
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;
}
int main()
{
vector< int > arr = { 3, 2, 4, 1, 2 };
int N = arr.size();
cout << minSum(arr, N);
return 0;
}
|
Java
public class GFG
{
static int minCost( int arr[], int n)
{
int a[] = new int [n + 1 ];
a[ 0 ] = 0 ;
for ( int i = 1 ; i <= n; i++) {
a[i] = a[i - 1 ] + arr[i - 1 ];
}
int ans = Integer.MAX_VALUE;
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;
}
public static void main(String[] args)
{
int arr[] = { 3 , 2 , 4 , 1 , 2 };
int N = arr.length;
System.out.println(minCost(arr, N));
}
}
|
Python3
def minSum(v, n):
a = [ 0 ]
for i in range ( 1 , n + 1 ):
a.append(a[ - 1 ] + v[i - 1 ])
ans = 10 * * 18
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
arr = [ 3 , 2 , 4 , 1 , 2 ]
N = len (arr)
print (minSum(arr, N))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int minCost( int [] arr, int n)
{
int [] a = new int [n + 1];
a[0] = 0;
for ( int i = 1; i <= n; i++) {
a[i] = a[i - 1] + arr[i - 1];
}
int ans = Int16.MaxValue;
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;
}
public static void Main(String[] args)
{
int [] arr = { 3, 2, 4, 1, 2 };
int N = arr.Length;
Console.WriteLine(minCost(arr, N));
}
}
|
Javascript
<script>
const minSum = (v, n) => {
let a = new Array(n + 1).fill(0);
a[0] = 0;
for (let i = 1; i <= n; i++) {
a[i] = a[i - 1] + v[i - 1];
}
let ans = 1e18;
for (let 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], a[j] - a[i],
a[k] - a[j],
a[n] - a[k]])
- Math.min(...[a[i], a[j] - a[i],
a[k] - a[j],
a[n] - a[k]]));
}
return ans;
}
let arr = [3, 2, 4, 1, 2];
let N = arr.length;
document.write(minSum(arr, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Brute Force in Python:
Approach:
- Define a function minimize_difference_1 that takes two inputs N and arr.
- Initialize a variable min_diff to infinity.
- Iterate over all possible split positions i, j, and k such that i < j < k < N.
- Compute the sum of the elements in the subarrays arr[:i], arr[i:j], arr[j:k], and arr[k:].
- Compute the maximum and minimum subarray sum from the four subarrays.
- Compute the difference between the maximum and minimum subarray sum.
- Update min_diff with the minimum value seen so far.
- Return min_diff as the answer.
C++
#include <bits/stdc++.h>
using namespace std;
int minimize_difference_1( int N, const vector< int >& arr) {
int min_diff = INT_MAX;
for ( int i = 1; i < N - 2; i++) {
for ( int j = i + 1; j < N - 1; j++) {
for ( int k = j + 1; k < N; k++) {
int a = accumulate(arr.begin(), arr.begin() + i, 0);
int b = accumulate(arr.begin() + i, arr.begin() + j, 0);
int c = accumulate(arr.begin() + j, arr.begin() + k, 0);
int d = accumulate(arr.begin() + k, arr.end(), 0);
int max_sum = max({a, b, c, d});
int min_sum = min({a, b, c, d});
int diff = max_sum - min_sum;
min_diff = min(min_diff, diff);
}
}
}
return min_diff;
}
int main() {
int N = 4;
vector< int > arr = {14, 6, 1, 7};
cout << minimize_difference_1(N, arr) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static int minimize_difference_1( int N, ArrayList<Integer> arr) {
int min_diff = Integer.MAX_VALUE;
for ( int i = 1 ; i < N - 2 ; i++) {
for ( int j = i + 1 ; j < N - 1 ; j++) {
for ( int k = j + 1 ; k < N; k++) {
int a = arr.subList( 0 , i).stream().mapToInt(Integer::intValue).sum();
int b = arr.subList(i, j).stream().mapToInt(Integer::intValue).sum();
int c = arr.subList(j, k).stream().mapToInt(Integer::intValue).sum();
int d = arr.subList(k, N).stream().mapToInt(Integer::intValue).sum();
int max_sum = Math.max(Math.max(a, b), Math.max(c, d));
int min_sum = Math.min(Math.min(a, b), Math.min(c, d));
int diff = max_sum - min_sum;
min_diff = Math.min(min_diff, diff);
}
}
}
return min_diff;
}
public static void main(String[] args) {
int N = 4 ;
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList( 14 , 6 , 1 , 7 ));
System.out.println(minimize_difference_1(N, arr));
}
}
|
Python3
def minimize_difference_1(N, arr):
min_diff = float ( 'inf' )
for i in range ( 1 , N - 2 ):
for j in range (i + 1 , N - 1 ):
for k in range (j + 1 , N):
a = sum (arr[:i])
b = sum (arr[i:j])
c = sum (arr[j:k])
d = sum (arr[k:])
max_sum = max (a, b, c, d)
min_sum = min (a, b, c, d)
diff = max_sum - min_sum
min_diff = min (min_diff, diff)
return min_diff
N = 4
arr = [ 14 , 6 , 1 , 7 ]
print (minimize_difference_1(N, arr))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static int MinimizeDifference1( int N, List< int > arr)
{
int minDiff = int .MaxValue;
for ( int i = 1; i < N - 2; i++) {
for ( int j = i + 1; j < N - 1; j++) {
for ( int k = j + 1; k < N; k++) {
int a = arr.GetRange(0, i).Sum();
int b = arr.GetRange(i, j - i).Sum();
int c = arr.GetRange(j, k - j).Sum();
int d = arr.GetRange(k, N - k).Sum();
int maxSum = Math.Max(Math.Max(a, b),
Math.Max(c, d));
int minSum = Math.Min(Math.Min(a, b),
Math.Min(c, d));
int diff = maxSum - minSum;
minDiff = Math.Min(minDiff, diff);
}
}
}
return minDiff;
}
public static void Main( string [] args)
{
int N = 4;
List< int > arr = new List< int >{ 14, 6, 1, 7 };
Console.WriteLine(
MinimizeDifference1(N, arr));
}
}
|
Javascript
function minimizeDifference(N, arr) {
let minDiff = Number.MAX_VALUE;
for (let i = 1; i < N - 2; i++) {
for (let j = i + 1; j < N - 1; j++) {
for (let k = j + 1; k < N; k++) {
let a = arr.slice(0, i).reduce((acc, val) => acc + val, 0);
let b = arr.slice(i, j).reduce((acc, val) => acc + val, 0);
let c = arr.slice(j, k).reduce((acc, val) => acc + val, 0);
let d = arr.slice(k).reduce((acc, val) => acc + val, 0);
let maxSum = Math.max(a, b, c, d);
let minSum = Math.min(a, b, c, d);
let diff = maxSum - minSum;
minDiff = Math.min(minDiff, diff);
}
}
}
return minDiff;
}
const N = 4;
const arr = [14, 6, 1, 7];
console.log(minimizeDifference(N, arr));
|
A time complexity of O(2^N * N) because we generate all 2^N partitions and for each partition, we need to calculate the maximum and minimum subarray sum, which takes O(N) time.
The space complexity is O(N) to store the input array.
Last Updated :
26 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...