Minimize difference between maximum and minimum Subarray sum by splitting Array into 4 parts
Last Updated :
23 Jul, 2025
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 <bits/stdc++.h>
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] = 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] = 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
<script>
// JavaScript code to implement the approach
// Function to find the minimum difference
// between maximum and minimum subarray sum
// after dividing the array into 4 subarrays
const minSum = (v, n) => {
let a = new Array(n + 1).fill(0);
// Precompute the prefix sum
a[0] = 0;
for (let i = 1; i <= n; i++) {
a[i] = a[i - 1] + v[i - 1];
}
// Initialize the ans with large value
let ans = 1e18;
// There are total four parts means 3 cuts.
// Here i, j, k represent those 3 cuts
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;
}
// Driver Code
let arr = [3, 2, 4, 1, 2];
let N = arr.length;
// Function call
document.write(minSum(arr, N));
// This code is contributed by rakeshsahni
</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++
// C++ code for above approach
#include <bits/stdc++.h>
using namespace std;
//Function to find the minimum difference
// between minimum and maximum subarray
int minimize_difference_1(int N, const vector<int>& arr) {
// Initialize the minimum difference as maximum possible value
int min_diff = INT_MAX;
// Iterate through possible first split positions
for (int i = 1; i < N - 2; i++) {
// Iterate through possible second split positions
for (int j = i + 1; j < N - 1; j++) {
// Iterate through possible third split positions
for (int k = j + 1; k < N; k++) {
// Calculate sums of the four subarrays created by the splits
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; // Output: 13
return 0;
}
// This code is contributed by Utkarsh Kumar
Java
import java.util.*;
class GFG {
// Function to find the minimum difference
// between minimum and maximum subarray
static int minimize_difference_1(int N, ArrayList<Integer> arr) {
// Initialize the minimum difference as maximum possible value
int min_diff = Integer.MAX_VALUE;
// Iterate through possible first split positions
for (int i = 1; i < N - 2; i++) {
// Iterate through possible second split positions
for (int j = i + 1; j < N - 1; j++) {
// Iterate through possible third split positions
for (int k = j + 1; k < N; k++) {
// Calculate sums of the four subarrays created by the splits
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;
}
// Driver code
public static void main(String[] args) {
int N = 4;
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(14, 6, 1, 7));
// Function call
System.out.println(minimize_difference_1(N, arr)); // Output: 13
}
}
// by phasing17
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)) # Output: 13
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
// Function to find the minimum difference
// between minimum and maximum subarray
static int MinimizeDifference1(int N, List<int> arr)
{
// Initialize the minimum difference as maximum
// possible value
int minDiff = int.MaxValue;
// Iterate through possible first split positions
for (int i = 1; i < N - 2; i++) {
// Iterate through possible second split
// positions
for (int j = i + 1; j < N - 1; j++) {
// Iterate through possible third split
// positions
for (int k = j + 1; k < N; k++) {
// Calculate sums of the four subarrays
// created by the splits
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;
}
// Driver code
public static void Main(string[] args)
{
int N = 4;
List<int> arr = new List<int>{ 14, 6, 1, 7 };
// Function call
Console.WriteLine(
MinimizeDifference1(N, arr)); // Output: 13
}
}
JavaScript
// Function to find the minimum difference
// between minimum and maximum subarray
function minimizeDifference(N, arr) {
// Initialize the minimum difference as maximum possible value
let minDiff = Number.MAX_VALUE;
// Iterate through possible first split positions
for (let i = 1; i < N - 2; i++) {
// Iterate through possible second split positions
for (let j = i + 1; j < N - 1; j++) {
// Iterate through possible third split positions
for (let k = j + 1; k < N; k++) {
// Calculate sums of the four subarrays created by the splits
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);
// Calculate the maximum and minimum sums
let maxSum = Math.max(a, b, c, d);
let minSum = Math.min(a, b, c, d);
// Calculate the difference and update minDiff if needed
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)); // Output: 13
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem