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> |
2
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 |
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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!