Minimum array elements required to be subtracted from either end to reduce K to 0
Last Updated :
23 Aug, 2021
Given an array arr[] consisting of N integers and an integer K, the task is to reduce K to 0 by removing an array element from either end of the array and subtracting it from K. If it is impossible to reduce K to 0, then print “-1”. Otherwise, print the minimum number of such operations required.
Examples:
Input: arr[] = {1, 3, 1, 1, 2}, K = 4
Output: 2
Explanation:
The given array is {1, 3, 1, 1, 2}
Operation1: Removing arr[0] (= 1) modifies arr[] to {3, 1, 1, 2}. Subtracting arr[0] from K reduces K to 4 – 1 = 3.
Operation2: Removing arr[0] (= 1) modifies arr[] to {1, 1, 2}. Subtracting arr[0] from K reduces K to 3 – 3 = 0.
Therefore, the total number of steps required is 2.
Input: arr[] = {1, 1, 3, 4}, K = 3
Output: -1
Approach: The given problem can be solved based on the following observations:
- Consider that X and Y elements are required to be removed from the front and back of the given array respectively, to reduce K to 0.
- Therefore, sum of the remaining array elements must be equal to (sum of array elements – K).
Therefore, from the above observation, the idea is to find the maximum length of subarray (say L) whose sum is equal to (sum of array elements – K). Therefore, print the value of (N – L) as the resultant minimum element that must be removed to reduce K to 0. If there doesn’t exist any such subarray, then print “-1”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int longestSubarray( int arr[],
int N, int K)
{
unordered_map< int , int > um;
int sum = 0, maxLen = 0;
for ( int i = 0; i < N; i++) {
sum += arr[i];
if (sum == K)
maxLen = i + 1;
if (um.find(sum) == um.end())
um[sum] = i;
if (um.find(sum - K) != um.end()) {
if (maxLen < (i - um[sum - K]))
maxLen = i - um[sum - K];
}
}
return maxLen;
}
void minRequiredOperation( int arr[],
int N, int K)
{
int TotalSum = 0;
for ( int i = 0; i < N; i++)
TotalSum += arr[i];
int maxLen = longestSubarray(
arr, N, TotalSum - K);
if (maxLen == -1) {
cout << -1;
}
else
cout << N - maxLen;
}
int main()
{
int arr[] = { 1, 3, 1, 1, 2 };
int K = 4;
int N = sizeof (arr) / sizeof (arr[0]);
minRequiredOperation(arr, N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int longestSubarray( int [] arr, int N, int K)
{
HashMap<Integer,
Integer> um = new HashMap<Integer,
Integer>();
int sum = 0 , maxLen = 0 ;
for ( int i = 0 ; i < N; i++)
{
sum += arr[i];
if (sum == K)
maxLen = i + 1 ;
if (!um.containsKey(sum))
um.put(sum, i);
if (um.containsKey(sum - K))
{
if (maxLen < (i - um.get(sum - K)))
maxLen = i - um.get(sum - K);
}
}
return maxLen;
}
static void minRequiredOperation( int [] arr, int N,
int K)
{
int TotalSum = 0 ;
for ( int i = 0 ; i < N; i++)
TotalSum += arr[i];
int maxLen = longestSubarray(arr, N, TotalSum - K);
if (maxLen == - 1 )
{
System.out.println(- 1 );
}
else
System.out.println(N - maxLen);
}
public static void main(String[] args)
{
int [] arr = { 1 , 3 , 1 , 1 , 2 };
int K = 4 ;
int N = arr.length;
minRequiredOperation(arr, N, K);
}
}
|
Python3
def longestSubarray(arr, N, K):
um = {}
sum , maxLen = 0 , 0
for i in range (N):
sum + = arr[i]
if ( sum = = K):
maxLen = i + 1
if ( sum not in um):
um[ sum ] = i
if (( sum - K) in um):
if (maxLen < (i - um[ sum - K])):
maxLen = i - um[ sum - K]
return maxLen
def minRequiredOperation(arr, N, K):
TotalSum = 0
for i in range (N):
TotalSum + = arr[i]
maxLen = longestSubarray(arr, N, TotalSum - K)
if (maxLen = = - 1 ):
print ( - 1 ,end = "")
else :
print (N - maxLen,end = "")
if __name__ = = '__main__' :
arr = [ 1 , 3 , 1 , 1 , 2 ]
K = 4
N = len (arr)
minRequiredOperation(arr, N, K)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int longestSubarray( int []arr,
int N, int K)
{
Dictionary< int , int > um = new Dictionary< int , int >();
int sum = 0, maxLen = 0;
for ( int i = 0; i < N; i++) {
sum += arr[i];
if (sum == K)
maxLen = i + 1;
if (!um.ContainsKey(sum))
um[sum] = i;
if (um.ContainsKey(sum - K)) {
if (maxLen < (i - um[sum - K]))
maxLen = i - um[sum - K];
}
}
return maxLen;
}
static void minRequiredOperation( int []arr,
int N, int K)
{
int TotalSum = 0;
for ( int i = 0; i < N; i++)
TotalSum += arr[i];
int maxLen = longestSubarray(
arr, N, TotalSum - K);
if (maxLen == -1) {
Console.WriteLine(-1);
}
else
Console.WriteLine(N - maxLen);
}
public static void Main()
{
int []arr = { 1, 3, 1, 1, 2 };
int K = 4;
int N = arr.Length;
minRequiredOperation(arr, N, K);
}
}
|
Javascript
<script>
function longestSubarray(arr, N, K)
{
let um = new Map();
let sum = 0, maxLen = 0;
for (let i = 0; i < N; i++)
{
sum += arr[i];
if (sum == K)
maxLen = i + 1;
if (!um.has(sum))
um.set(sum, i);
if (um.has(sum - K))
{
if (maxLen < (i - um.get(sum - K)))
maxLen = i - um.get(sum - K);
}
}
return maxLen;
}
function minRequiredOperation(arr, N, K)
{
let TotalSum = 0;
for (let i = 0; i < N; i++)
TotalSum += arr[i];
let maxLen = longestSubarray(
arr, N, TotalSum - K);
if (maxLen == -1)
{
document.write(-1);
}
else
document.write(N - maxLen);
}
let arr = [ 1, 3, 1, 1, 2 ];
let K = 4;
let N = arr.length
minRequiredOperation(arr, N, K);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...