Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum elements that can be removed from front of two arrays such that their sum is at most K
Next article icon

Minimum number of elements to be removed such that the sum of the remaining elements is equal to k

Last Updated : 05 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of integers and an integer k, the task is to find the minimum number of integers that need to be removed from the array such that the sum of the remaining elements is equal to k. If we cannot get the required sum the print -1.
Examples: 
 

Input: arr[] = {1, 2, 3}, k = 3 
Output: 1 
Either remove 1 and 2 to reduce the array to {3} 
or remove 3 to get the array {1, 2}. Both have equal sum i.e. 3 
But removing 3 requires only a single removal.
Input: arr[] = {1, 3, 2, 5, 6}, k = 5 
Output: 3 
 

 

Approach: The idea is to use a sliding window and variables j initialize it to 0, min_num to store the answer and sum to store the current sum. Keep on adding the elements of the array to the variable sum, till it becomes greater than or equal to k, if it is equal to k, then update the min_num as minimum of min_num and (n -(i+1) +j) where n is the number of integers in array and i is the current index, else if it is greater than k, then start decrementing the sum by removing the values of the array from sum till the sum becomes less than or equal to k and also increment the value of j, if sum is equal to k, then once again update min_num. Repeat this whole process till the end of the array.
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 number of
// integers that need to be removed from the
// array to form a sub-array with sum k
int FindMinNumber(int arr[], int n, int k)
{
    int i = 0;
    int j = 0;
 
    // Stores the minimum number of
    // integers that need to be removed
    // from the array
    int min_num = INT_MAX;
 
    bool found = false;
 
    int sum = 0;
 
    while (i < n) {
 
        sum = sum + arr[i];
 
        // If current sum is equal to
        // k, update min_num
        if (sum == k) {
            min_num = min(min_num, ((n - (i + 1)) + j));
            found = true;
        }
 
        // If current sum is greater than k
        else if (sum > k) {
 
            // Decrement the sum until it
            // becomes less than or equal to k
            while (sum > k) {
                sum = sum - arr[j];
                j++;
            }
            if (sum == k) {
                min_num = min(min_num, ((n - (i + 1)) + j));
                found = true;
            }
        }
 
        i++;
    }
 
    if (found)
        return min_num;
 
    return -1;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 3, 2, 5, 6 };
    int n = sizeof(arr) / sizeof(int);
    int k = 5;
 
    cout << FindMinNumber(arr, n, k);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
class GFG
{
     
// Function to return the minimum number of
// integers that need to be removed from the
// array to form a sub-array with sum k
static int FindMinNumber(int arr[], int n, int k)
{
    int i = 0;
    int j = 0;
 
    // Stores the minimum number of
    // integers that need to be removed
    // from the array
    int min_num = Integer.MAX_VALUE;
 
    boolean found = false;
 
    int sum = 0;
 
    while (i < n)
    {
 
        sum = sum + arr[i];
 
        // If current sum is equal to
        // k, update min_num
        if (sum == k)
        {
            min_num = Math.min(min_num,
                             ((n - (i + 1)) + j));
            found = true;
        }
 
        // If current sum is greater than k
        else if (sum > k)
        {
 
            // Decrement the sum until it
            // becomes less than or equal to k
            while (sum > k)
            {
                sum = sum - arr[j];
                j++;
            }
            if (sum == k)
            {
                min_num = Math.min(min_num,
                                 ((n - (i + 1)) + j));
                found = true;
            }
        }
 
        i++;
    }
 
    if (found)
        return min_num;
 
    return -1;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 3, 2, 5, 6 };
    int n = arr.length;
    int k = 5;
 
    System.out.println(FindMinNumber(arr, n, k));
}
}
 
// This code is contributed by Code_Mech
 
 

Python3




# Python3 implementation of the approach
 
# Function to return the minimum number of
# integers that need to be removed from the
# array to form a sub-array with Sum k
def FindMinNumber(arr, n, k):
    i = 0
    j = 0
 
    # Stores the minimum number of
    # integers that need to be removed
    # from the array
    min_num = 10**9
 
    found = False
 
    Sum = 0
 
    while (i < n):
 
        Sum = Sum + arr[i]
 
        # If current Sum is equal to
        # k, update min_num
        if (Sum == k):
            min_num = min(min_num,
                        ((n - (i + 1)) + j))
            found = True
         
        # If current Sum is greater than k
        elif (Sum > k):
 
            # Decrement the Sum until it
            # becomes less than or equal to k
            while (Sum > k):
                Sum = Sum - arr[j]
                j += 1
            if (Sum == k):
                min_num = min(min_num,
                            ((n - (i + 1)) + j))
                found = True
             
        i += 1
 
    if (found):
        return min_num
 
    return -1
 
# Driver code
arr = [1, 3, 2, 5, 6]
n = len(arr)
k = 5
 
print(FindMinNumber(arr, n, k))
 
# This code is contributed by mohit kumar
 
 

C#




// C# implementation of the approach
using System;
 
class GFG
{
     
// Function to return the minimum number of
// integers that need to be removed from the
// array to form a sub-array with sum k
static int FindMinNumber(int[] arr, int n, int k)
{
    int i = 0;
    int j = 0;
 
    // Stores the minimum number of
    // integers that need to be removed
    // from the array
    int min_num = int.MaxValue;
 
    bool found = false;
 
    int sum = 0;
 
    while (i < n)
    {
 
        sum = sum + arr[i];
 
        // If current sum is equal to
        // k, update min_num
        if (sum == k)
        {
            min_num = Math.Min(min_num,
                            ((n - (i + 1)) + j));
            found = true;
        }
 
        // If current sum is greater than k
        else if (sum > k)
        {
 
            // Decrement the sum until it
            // becomes less than or equal to k
            while (sum > k)
            {
                sum = sum - arr[j];
                j++;
            }
            if (sum == k)
            {
                min_num = Math.Min(min_num,
                                ((n - (i + 1)) + j));
                found = true;
            }
        }
 
        i++;
    }
 
    if (found)
        return min_num;
 
    return -1;
}
 
// Driver code
public static void Main()
{
    int[] arr = { 1, 3, 2, 5, 6 };
    int n = arr.Length;
    int k = 5;
 
    Console.WriteLine(FindMinNumber(arr, n, k));
}
}
 
// This code is contributed by Code_Mech
 
 

PHP




<?php
// PHP implementation of the approach
// Function to return the minimum number of
// integers that need to be removed from the
// array to form a sub-array with sum k
function FindMinNumber($arr,$n,$k)
{
    $i = 0;
    $j = 0;
 
    // Stores the minimum number of
    // integers that need to be removed
    // from the array
    $min_num = PHP_INT_MAX;
 
    $found = false;
 
    $sum = 0;
 
    while ($i < $n)
    {
 
        $sum = $sum + $arr[$i];
 
        // If current sum is equal to
        // k, update min_num
        if ($sum == $k)
        {
            $min_num = min($min_num,
                            (($n - ($i + 1)) + $j));
            $found = true;
        }
 
        // If current sum is greater than k
        else if ($sum > $k)
        {
 
            // Decrement the sum until it
            // becomes less than or equal to k
            while ($sum > $k)
            {
                $sum = $sum - $arr[$j];
                $j++;
            }
            if ($sum == $k)
            {
                $min_num =min($min_num,
                                (($n - ($i + 1)) + $j));
                $found = true;
            }
        }
 
        $i++;
    }
 
    if ($found)
        return $min_num;
 
    return -1;
}
 
// Driver code
$arr = array( 1, 3, 2, 5, 6 );
$n = sizeof($arr);
$k = 5;
 
echo(FindMinNumber($arr, $n, $k));
 
// This code is contributed by Code_Mech
 
 

Javascript




<script>
// Javascript implementation of the approach
 
// Function to return the minimum number of
// integers that need to be removed from the
// array to form a sub-array with sum k
function FindMinNumber(arr,n,k)
{
    let i = 0;
    let j = 0;
   
    // Stores the minimum number of
    // integers that need to be removed
    // from the array
    let min_num = Number.MAX_VALUE; 
    let found = false;
    let sum = 0;
    while (i < n)
    {
   
        sum = sum + arr[i];
   
        // If current sum is equal to
        // k, update min_num
        if (sum == k)
        {
            min_num = Math.min(min_num,
                             ((n - (i + 1)) + j));
            found = true;
        }
   
        // If current sum is greater than k
        else if (sum > k)
        {
   
            // Decrement the sum until it
            // becomes less than or equal to k
            while (sum > k)
            {
                sum = sum - arr[j];
                j++;
            }
            if (sum == k)
            {
                min_num = Math.min(min_num,
                                 ((n - (i + 1)) + j));
                found = true;
            }
        }
   
        i++;
    }
   
    if (found)
        return min_num;
   
    return -1;
}
 
// Driver code
let arr = [1, 3, 2, 5, 6 ];
let n = arr.length;
let k = 5;
document.write(FindMinNumber(arr, n, k));
 
// This code is contributed by patel2127
</script>
 
 
Output: 
3

 

Time Complexity: O(N)
Auxiliary Space: O(1) 



Next Article
Maximum elements that can be removed from front of two arrays such that their sum is at most K
author
sakshi_srivastava
Improve
Article Tags :
  • Algorithms
  • Arrays
  • Data Structures
  • DSA
  • sliding-window
Practice Tags :
  • Algorithms
  • Arrays
  • Data Structures
  • sliding-window

Similar Reads

  • Maximum elements that can be removed from front of two arrays such that their sum is at most K
    Given an integer K and two arrays A[] and B[] consisting of N and M integers, the task is to maximize the number of elements that can be removed from the front of either array according to the following rules: Remove an element from the front of either array A[] and B[] such that the value of the re
    15+ min read
  • Sum of elements of all partitions of number such that no element is less than K
    Given an integer N, the task is to find an aggregate sum of all integer partitions of this number such that each partition does not contain any integer less than K. Examples: Input: N = 6 and K = 2 Output: 24 In this case, there are 4 valid partitions. 1) {6} 2) {4, 2} 3) {3, 3} 4) {2, 2, 2} Therefo
    9 min read
  • Minimize count of array elements to be removed such that at least K elements are equal to their index values
    Given an array arr[](1- based indexing) consisting of N integers and a positive integer K, the task is to find the minimum number of array elements that must be removed such that at least K array elements are equal to their index values. If it is not possible to do so, then print -1. Examples: Input
    13 min read
  • Find the minimum number of elements that should be removed to make an array good
    Given an array of size N and an integer K. The array consists of only digits {0, 1, 2, 3, ...k-1}. The task is to make array good by removing some of the elements. The array of length x is called good if x is divisible by k and one can split the given array into x/k subsequences and each of form {0,
    6 min read
  • Length of smallest subarray to be removed to make sum of remaining elements divisible by K
    Given an array arr[] of integers and an integer K, the task is to find the length of the smallest subarray that needs to be removed such that the sum of remaining array elements is divisible by K. Removal of the entire array is not allowed. If it is impossible, then print "-1". Examples: Input: arr[
    11 min read
  • Minimum number of array indices required to be selected to make the sum of a set greater than another
    Given two arrays arr[] and brr[] of size N and an integer K. Consider two sets A, contains K initially, and B, initially empty. In each operation, an index is required to be selected. For every selected index, say i, arr[i] and brr[i] is added to B. For every unselected index, arr[i] is added to A.
    9 min read
  • Minimum removals required such that sum of remaining array modulo M is X
    Given an array arr[] consisting of N positive integers and the integers X and M, where 0 <= X < M, the task is to find the minimum number of elements required to be removed such that sum of the remaining array modulo M is equal to X. Print -1 if not possible. Examples: Input: arr[] = {3, 2, 1,
    15+ min read
  • Minimum swaps to minimize the sum of first K elements of the Permutation
    Given a permutation A[] of first N integers (i.e. array contains integers from 1 to N exactly once) and an integer K, the task is to find the minimum number of swaps needed to minimize the sum of the first K elements of the array. Examples: Input: N = 4, K = 2, A[] = {3, 4, 1, 2}Output: 2Explanation
    6 min read
  • Minimum size of subset of pairs whose sum is at least the remaining array elements
    Given two arrays A[] and B[] both consisting of N positive integers, the task is to find the minimum size of the subsets of pair of elements (A[i], B[i]) such that the sum of all the pairs of subsets is at least the sum of remaining array elements A[] which are not including in the subset i.e., (A[0
    11 min read
  • Minimum pairs required to be removed such that the array does not contain any pair with sum K
    Given an array arr[] of size N and an integer K, the task is to find the minimum count of pairs required to be removed such that no pair exists in the array whose sum of elements is equal to K. Examples: Input: arr[] = { 3, 1, 3, 4, 3 }, K = 6 Output: 1 Explanation: Removing the pair (arr[0], arr[2]
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences