Minimum value to add to arr[i] so that an array can be split at index i with equal sum
Last Updated :
21 Nov, 2022
Given an array arr[] of integers, the task is to find the minimum non-negative integer k such that there exists an index j in the given array such that when arr[j] is updated as arr[j] + k, the sum of elements of an array from index arr[0] to arr[j] is equal to the sum of elements from arr[j + 1] to arr[n - 1] i.e.
arr[0] + arr[1] + ... + arr[j] = arr[j + 1] + arr[j + 2] + ... + arr[n - 1]
If no such k exists then print -1.
Examples:
Input: arr[] = {6, 7, 1, 3, 8, 2, 4}
Output: 3
If 3 is added to 1 sum of elements from index 0 to 2 and 3 to 6 will be equal to 17.
Input: arr[] = {7, 3}
Output: -1
A simple approach is to run two loops. For every element, find the difference between sums of elements on the left and right. Finally, return the minimum difference between the two sums.
An efficient approach: is to first calculate the prefix sum and store in an array pre[] where pre[i] stores the sum of array elements from arr[0] to arr[i]. For each index, if the sum of elements left to it (including the element itself i.e. pre[i]) is less than or equal to the sum of right elements (pre[n - 1] - pre[i]) then update the value of k as min(k, (pre[n - 1] - pre[i]) - pre[i])
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimum value k to be added
int FindMinNum(int arr[], int n)
{
// Array to store prefix sum
int pre[n];
// Initialize the prefix value for first index
// as the first element of the array
pre[0] = arr[0];
// Compute the prefix sum for rest of the indices
for (int i = 1; i < n; i++)
pre[i] = pre[i - 1] + arr[i];
int k = INT_MAX;
for (int i = 0; i < n - 1; i++) {
// Sum of elements from arr[i + 1] to arr[n - 1]
int rightSum = pre[n - 1] - pre[i];
// If sum on the right side of the ith element
// is greater than or equal to the sum on the
// left side then update the value of k
if (rightSum >= pre[i])
k = min(k, rightSum - pre[i]);
}
if (k != INT_MAX)
return k;
return -1;
}
// Driver code
int main()
{
int arr[] = { 6, 7, 1, 3, 8, 2, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << FindMinNum(arr, n);
return 0;
}
Java
// Java implementation of the approach
class GfG
{
// Function to return the minimum value k to be added
static int FindMinNum(int arr[], int n)
{
// Array to store prefix sum
int pre[] = new int[n];
// Initialize the prefix value for first index
// as the first element of the array
pre[0] = arr[0];
// Compute the prefix sum for rest of the indices
for (int i = 1; i < n; i++)
pre[i] = pre[i - 1] + arr[i];
int k = Integer.MAX_VALUE;
for (int i = 0; i < n - 1; i++)
{
// Sum of elements from arr[i + 1] to arr[n - 1]
int rightSum = pre[n - 1] - pre[i];
// If sum on the right side of the ith element
// is greater than or equal to the sum on the
// left side then update the value of k
if (rightSum >= pre[i])
k = Math.min(k, rightSum - pre[i]);
}
if (k != Integer.MAX_VALUE)
return k;
return -1;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 6, 7, 1, 3, 8, 2, 4 };
int n = arr.length;
System.out.println(FindMinNum(arr, n));
}
}
// This code is contributed by Prerna Saini
Python3
# Python 3 implementation of the approach
import sys
# Function to return the minimum
# value k to be added
def FindMinNum(arr, n):
# Array to store prefix sum
pre = [0 for i in range(n)]
# Initialize the prefix value for first
# index as the first element of the array
pre[0] = arr[0]
# Compute the prefix sum for rest
# of the indices
for i in range(1, n, 1):
pre[i] = pre[i - 1] + arr[i]
k = sys.maxsize
for i in range(n - 1):
# Sum of elements from arr[i + 1] to arr[n - 1]
rightSum = pre[n - 1] - pre[i]
# If sum on the right side of the ith element
# is greater than or equal to the sum on the
# left side then update the value of k
if (rightSum >= pre[i]):
k = min(k, rightSum - pre[i])
if (k != sys.maxsize):
return k
return -1
# Driver code
if __name__ == '__main__':
arr = [6, 7, 1, 3, 8, 2, 4]
n = len(arr)
print(FindMinNum(arr, n))
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the approach
using System;
class GfG
{
// Function to return the minimum value k to be added
static int FindMinNum(int []arr, int n)
{
// Array to store prefix sum
int []pre = new int[n];
// Initialize the prefix value for first index
// as the first element of the array
pre[0] = arr[0];
// Compute the prefix sum for rest of the indices
for (int i = 1; i < n; i++)
pre[i] = pre[i - 1] + arr[i];
int k = int.MaxValue;
for (int i = 0; i < n - 1; i++)
{
// Sum of elements from arr[i + 1] to arr[n - 1]
int rightSum = pre[n - 1] - pre[i];
// If sum on the right side of the ith element
// is greater than or equal to the sum on the
// left side then update the value of k
if (rightSum >= pre[i])
k = Math.Min(k, rightSum - pre[i]);
}
if (k != int.MaxValue)
return k;
return -1;
}
// Driver code
public static void Main()
{
int []arr = { 6, 7, 1, 3, 8, 2, 4 };
int n = arr.Length;
Console.WriteLine(FindMinNum(arr, n));
}
}
// This code is contributed by Ryuga
PHP
<?php
// PHP implementation of the approach
// Function to return the minimum
// value k to be added
function FindMinNum($arr, $n)
{
// Array to store prefix sum
$pre = array();
// Initialize the prefix value for first index
// as the first element of the array
$pre[0] = $arr[0];
// Compute the prefix sum for
// rest of the indices
for ($i = 1; $i < $n; $i++)
$pre[$i] = $pre[$i - 1] + $arr[$i];
$k = PHP_INT_MAX;
for ($i = 0; $i < $n - 1; $i++)
{
// Sum of elements from arr[i + 1] to arr[n - 1]
$rightSum = $pre[$n - 1] - $pre[$i];
// If sum on the right side of the ith element
// is greater than or equal to the sum on the
// left side then update the value of k
if ($rightSum >= $pre[$i])
$k = min($k, $rightSum - $pre[$i]);
}
if ($k != PHP_INT_MAX)
return $k;
return -1;
}
// Driver code
$arr = array(6, 7, 1, 3, 8, 2, 4);
$n = sizeof($arr);
echo FindMinNum($arr, $n);
// This code is contributed by Akanksha Rai
?>
JavaScript
<script>
//Javascript Implementation
// Function to return the minimum value k to be added
function FindMinNum(arr, n)
{
// Array to store prefix sum
var pre = new Array(n);
// Initialize the prefix value for first index
// as the first element of the array
pre[0] = arr[0];
// Compute the prefix sum for rest of the indices
for (var i = 1; i < n; i++)
pre[i] = pre[i - 1] + arr[i];
var k = Number.MAX_VALUE;
for (var i = 0; i < n - 1; i++) {
// Sum of elements from arr[i + 1] to arr[n - 1]
var rightSum = pre[n - 1] - pre[i];
// If sum on the right side of the ith element
// is greater than or equal to the sum on the
// left side then update the value of k
if (rightSum >= pre[i])
k = Math.min(k, rightSum - pre[i]);
}
if (k != Number.MAX_VALUE)
return k;
return -1;
}
/* Driver code*/
var arr = [6, 7, 1, 3, 8, 2, 4];
var n = arr.length;
document.write(FindMinNum(arr, n))
// This code is contributed by shubhamsingh10
</script>
Time Complexity : O(n)
Auxiliary Space : O(n)
Further optimization: We can avoid the use of extra space using the below steps.
- First, compute the sum of all the elements and store it in a variable sum.
- Iterate a loop for every index where the left sum at any index can be computed by keep on adding the current elements to the leftsum variable.
- The rightsum can be calculated by keep on subtracting the elements at every index from the sum variable.
- For any ith index if we find that the rightsum is greater than the leftsum then we update the value of k.
Below is the code for the above approach.
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimum value k to be added
int FindMinNum(int arr[], int n)
{
int sum = 0; // initialize sum of whole array
int leftsum = 0; // initialize leftsum
int k = INT_MAX;
/* Find sum of the whole array */
for (int i = 0; i < n; ++i)
sum += arr[i];
for (int i = 0; i < n; ++i) {
sum -= arr[i]; // sum is now right sum for index i
leftsum += arr[i]; // add current element to leftsum
// If sum on the right side of the ith element
// is greater than or equal to the sum on the
// left side then update the value of k
if (sum >= leftsum)
k = min(k, sum - leftsum);
}
if (k != INT_MAX)
return k;
return -1;
}
// Driver code
int main()
{
int arr[] = { 6, 7, 1, 3, 8, 2, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << FindMinNum(arr, n);
return 0;
}
// This code is contributed by Pushpesh raj
Java
// Java implementation of the approach
class GfG {
// Function to return the minimum value k to be added
static int FindMinNum(int arr[], int n)
{
int sum = 0; // initialize sum of whole array
int leftsum = 0; // initialize leftsum
int k = Integer.MAX_VALUE;
/* Find sum of the whole array */
for (int i = 0; i < n; ++i)
sum += arr[i];
for (int i = 0; i < n; ++i) {
sum -= arr[i]; // sum is now right sum for index
// i
leftsum
+= arr[i]; // add current element to leftsum
// If sum on the right side of the ith element
// is greater than or equal to the sum on the
// left side then update the value of k
if (sum >= leftsum)
k = Math.min(k, sum - leftsum);
}
if (k != Integer.MAX_VALUE)
return k;
return -1;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 6, 7, 1, 3, 8, 2, 4 };
int n = arr.length;
System.out.println(FindMinNum(arr, n));
}
}
// This code is contributed by Pushpesh Raj.
Python3
import sys
import math
# Python 3 implementation of the approach
class GfG :
# Function to return the minimum value k to be added
@staticmethod
def FindMinNum( arr, n) :
sum = 0
# initialize sum of whole array
leftsum = 0
# initialize leftsum
k = sys.maxsize
# Find sum of the whole array
i = 0
while (i < n) :
sum += arr[i]
i += 1
i = 0
while (i < n) :
sum -= arr[i]
# sum is now right sum for index
# i
leftsum += arr[i]
# add current element to leftsum
# If sum on the right side of the ith element
# is greater than or equal to the sum on the
# left side then update the value of k
if (sum >= leftsum) :
k = min(k,sum - leftsum)
i += 1
if (k != sys.maxsize) :
return k
return -1
# Driver code
@staticmethod
def main( args) :
arr = [6, 7, 1, 3, 8, 2, 4]
n = len(arr)
print(GfG.FindMinNum(arr, n))
if __name__=="__main__":
GfG.main([])
# This code is contributed by utkarshshirode02.
C#
// C# implementation of the approach
using System;
class GfG {
// Function to return the minimum value k to be added
static int FindMinNum(int[] arr, int n)
{
int sum = 0; // initialize sum of whole array
int leftsum = 0; // initialize leftsum
int k = int.MaxValue;
/* Find sum of the whole array */
for (int i = 0; i < n; ++i)
sum += arr[i];
for (int i = 0; i < n; ++i) {
sum -= arr[i]; // sum is now right sum for index
// i
leftsum
+= arr[i]; // add current element to leftsum
// If sum on the right side of the ith element
// is greater than or equal to the sum on the
// left side then update the value of k
if (sum >= leftsum)
k = Math.Min(k, sum - leftsum);
}
if (k != int.MaxValue)
return k;
return -1;
}
// Driver code
public static void Main()
{
int[] arr = { 6, 7, 1, 3, 8, 2, 4 };
int n = arr.Length;
Console.WriteLine(FindMinNum(arr, n));
}
}
// This code is contributed by Pushpesh Raj
JavaScript
<script>
//Javascript Implementation
// Function to return the minimum value k to be added
function FindMinNum(arr, n)
{
var sum = 0; // initialize sum of whole array
var leftsum = 0; // initialize leftsum
var k = Number.MAX_VALUE;
/* Find sum of the whole array */
for (var i = 0; i < n; ++i)
sum += arr[i];
for (var i = 0; i < n; ++i)
{
sum -= arr[i]; // sum is now right sum for index i
leftsum+=arr[i]; // add current element to leftsum
// If sum on the right side of the ith element
// is greater than or equal to the sum on the
// left side then update the value of k
if (sum >= leftsum)
k = Math.min(k, sum - leftsum);
}
if (k != Number.MAX_VALUE)
return k;
return -1;
}
/* Driver code*/
var arr = [6, 7, 1, 3, 8, 2, 4];
var n = arr.length;
document.write(FindMinNum(arr, n))
// This code is contributed by Pushpesh raj
</script>
The idea is similar to optimized solution of equilibrium index problem.
Time Complexity : O(n)
Auxiliary Space : O(1)
Similar Reads
Minimum value to be added to the prefix sums at each array indices to make them positive Given an array arr[] consisting of N of integers, the task is to find the minimum positive value S that needs to be added such that the prefix sum at each index of the given array after adding S is always positive. Examples: Input: arr[] = {-3, 2, -3, 4, 2}Output: 5Explanation:For S = 5, prefix sums
5 min read
Minimum increments to modify array such that value of any array element can be splitted to make all remaining elements equal Given an array arr[] consisting of N elements, the task is to find the minimum number of increments required to be performed on the given array such that after selecting any array element at any index and splitting its value to the other array elements makes all other N - 1 elements equal. Examples:
6 min read
Find the minimum value to be added so that array becomes balanced Given an array of even size, task is to find minimum value that can be added to an element so that array become balanced. An array is balanced if the sum of the left half of the array elements is equal to the sum of right half. Suppose, we have an array 1 3 1 2 4 3. The Sum of first three elements i
5 min read
Find an array B with at least arr[i] elements in B not equal to the B[i] Given an array arr[] of size N, the task is to find an array of size N, such that for every ith element of the array arr[], the output array should contain at least arr[i] elements that are not equal to the ith element of the output array. If there exists no such array, then print "Impossible". Exam
9 min read
Minimum count of elements to be inserted in Array to form all values in [1, K] using subset sum Given a sorted array arr[] consisting of N integers, and an integer K, the task is to find the minimum number of elements to be inserted in the array such that any value in the range [1, K] can be formed by adding elements of any subset of the modified array. Examples: Input: arr[] = {1, 3}, K = 6Ou
7 min read
Minimum numbers to be appended such that mean of Array is equal to 1 Given an array arr[ ] of size N, the task is find minimum number of operation required to make mean of Array arr[ ] equal to 1. In one operation, a non-negative number can be appended in the end of the array. Examples: Input: N = 3, arr = {1, 1, 1}Output: 0Explanation:As it can be seen that mean of
4 min read
Smallest index that splits an array into two subarrays with equal product Given an array(1-based indexing) arr[] consisting of N non zero integers, the task is to find the leftmost index i such that the product of all the elements of the subarrays arr[1, i] and arr[i + 1, N] is the same. Examples: Input: arr[] = {1, 2, 3, 3, 2, 1}Output: 3Explanation: Index 3 generates su
10 min read
Find the sums for which an array can be divided into sub-arrays of equal sum Given an array of integers arr[], the task is to find all the values for sum such that for a value sum[i] the array can be divided into sub-arrays of sum equal to sum[i]. If array cannot be divided into sub-arrays of equal sum then print -1. Examples: Input: arr[] = {2, 2, 2, 1, 1, 2, 2} Output: 2 4
10 min read
Minimum sum of values subtracted from array elements to make all array elements equal Given an array arr[] consisting of N positive integers, the task is to find the sum of all the array elements required to be subtracted from each array element such that remaining array elements are all equal. Examples: Input: arr[] = {1, 2}Output: 1Explanation: Subtracting 1 from arr[1] modifies ar
4 min read
Split array into two subsequences having minimum count of pairs with sum equal to X Given an array arr[] consisting of N integers and an integer X, the task is to split the array into two subsequences such that the number of pairs having a sum equal to X is minimum in both the arrays. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, X = 7 Output: The First Array is - 1 2 3The Second Ar
8 min read