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:
Maximize value of K such that a subsequence with sum i exists for each integer i in range [1, K]
Next article icon

Minimum number of insertions required such that first K natural numbers can be obtained as sum of a subsequence of the array

Last Updated : 09 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N positive integers and a positive integer K, the task is to find the minimum number of elements that are required to be inserted such that all numbers from the range [1, K] can be obtained as the sum of any subsequence of the array.

Examples:

Input: arr[] = {1, 3, 5}, K = 10
Output: 1
Explanation:
Appending the element {1} to the array modifies the array to {1, 3, 5, 1}. Now the all the sum over the range [1, K] can be obtained as:

  1. Sum 1: The elements are {1}.
  2. Sum 2: The elements are {1, 1}.
  3. Sum 3: The elements are {3}.
  4. Sum 4: The elements are {1. 3}.
  5. Sum 5: The elements are {1, 3, 1}.
  6. Sum 6: The elements are {1, 5}.
  7. Sum 7: The elements are {1, 5, 1}.
  8. Sum 8: The elements are {3, 5}.
  9. Sum 9: The elements are {1, 3, 5}.
  10. Sum 10: The elements are {1, 3, 5, 1}.

Input: arr[] = {2, 6, 8, 12, 19}, K = 20
Output: 2

Approach: The given problem can be solved by sorting the array in increasing order and then try to make the sum value over the range [1, K] using the fact that if the sum of array elements X, then all the values over the range [1, X] can be formed. Otherwise, it is required to insert the value (sum + 1) as an array element. Follow the steps below to solve the problem:

  • Sort the array arr[] in increasing order.
  • Initialize the variable, say index as 0 to maintain the index of the array element and count as 0 to store the resultant total elements added.
  • If the value of arr[0] is greater than 1, then 1 needs to be appended, so increase the value of the count by 1. Otherwise, increase the value of the index by 1.
  • Initialize the variable, say expect as 2 to maintain the next value expected in the range from 1 to K to be formed from the array arr[].
  • Iterate a loop until the value of expect is at most K and perform the following steps:
    • If the index is greater than equal to N or arr[index] is greater than the value of expect, then increase the value of count by 1 and multiply the value of expect by 2.
    • Otherwise, increase the value of expect by arr[index] and increase the value of the index by 1.
  • After completing the above steps, print the value of count as the result.

Below is the implementation of the above approach.

C++14




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum number of elements that must
// be added to make the sum of array element over the range
// [1, K]
void findMinimumNumberOfElements(int n, int k, int arr[])
{
    // Sort the given array
    sort(arr, arr + n);
 
    // Stores the index for the array
    int index = 0, count = 0;
    // If 1 is not present, then append it
    if (arr[0] > 1)
        ++count;
    // Move on to next index
    else
        ++index;
 
    // The expected value in the array
    long long expect = 2;
    while (expect <= k) {
        // Need to append this number
        if (index >= n || arr[index] > expect) {
            ++count;
            expect += expect;
        }
 
        // Otherwise, expand the range by current number
        else {
            expect += arr[index];
            ++index;
        }
    }
    // Print the answer
    cout << count;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 6, 8, 12, 19 };
    int K = 20;
    int N = sizeof(arr) / sizeof(arr[0]);
    findMinimumNumberOfElements(N, K, arr);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)
 
 

C




// C program for the above approach
 
#include <stdio.h>
#include <stdlib.h>
 
int cmpfunc(const void* a, const void* b)
{
    return (*(int*)a - *(int*)b);
}
 
// Function to find the minimum number of elements that must
// be added to make the sum of array element over the range
// [1, K]
void findMinimumNumberOfElements(int n, int k, int arr[])
{
    // Sort the given array
    qsort(arr, n, sizeof(int), cmpfunc);
 
    // Stores the index for the array
    int index = 0, count = 0;
    // If 1 is not present, then append it
    if (arr[0] > 1)
        ++count;
    // Move on to next index
    else
        ++index;
 
    // The expected value in the array
    long long expect = 2;
    while (expect <= k) {
        // Need to append this number
        if (index >= n || arr[index] > expect) {
            ++count;
            expect += expect;
        }
 
        // Otherwise, expand the range by current number
        else {
            expect += arr[index];
            ++index;
        }
    }
    // Print the answer
    printf("%d", count);
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 6, 8, 12, 19 };
    int K = 20;
    int N = sizeof(arr) / sizeof(arr[0]);
    findMinimumNumberOfElements(N, K, arr);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)
 
 

Java




// Java program for the above approach
import java.io.*;
import java.util.Arrays;
 
class GFG {
 
    // Function to find the minimum number of elements that
    // must be added to make the sum of array element over
    // the range [1, K]
    static void findMinimumNumberOfElements(int n, int k, int[] arr)
    {
        // Sort the given array
        Arrays.sort(arr);
 
        // Stores the index for the array
        int index = 0, count = 0;
        // If 1 is not present, then append it
 
        if (arr[0] > 1)
            ++count;
        // Move on to next index
        else
            ++index;
 
        // The expected value in the array
        long expect = 2;
        while (expect <= k) {
 
            // Need to append this number
            if (index >= n || arr[index] > expect) {
                ++count;
                expect += expect;
            }
 
            // Otherwise, expand the range by current number
            else {
                expect += arr[index];
                ++index;
            }
        }
 
        // Print the answer
        System.out.println(count);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 2, 6, 8, 12, 19 };
        int K = 20;
        int N = arr.length;
        findMinimumNumberOfElements(N, K, arr);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)
 
 

Python3




# Python 3 program for the above approach
 
# Function to find the minimum number
# of elements that must be added to
# make the sum of array element over
# the range [1, K]
def findMinimumNumberOfElements(n, k, arr):
    # Sort the given array
    arr.sort()
 
    # Stores the index for the
    # array
    index = 0
    count = 0
 
    if (arr[0] > 1):
        # If 1 is not present, then
        # append it
        count += 1
 
    # Move on to next index
    else:
        index += 1
 
    # The expected value in the array
    expect = 2
    while (expect <= k):
 
        # Need to append this number
        if (index >= n or arr[index] > expect):
            count += 1
            expect += expect
 
        # Otherwise, expand the range
        # by current number
        else:
            expect += arr[index]
            index += 1
 
    # Print the answer
    print(count)
 
# Driver Code
if __name__ == '__main__':
    arr = [2, 6, 8, 12, 19]
    K = 20
    N = len(arr)
    findMinimumNumberOfElements(N, K, arr)
     
    # This code is contributed by ipg2016107.
 
 

C#




// C# program for the above approach
using System;
 
class GFG {
     
 // Function to find the minimum number
    // of elements that must be added to
    // make the sum of array element over
    // the range [1, K]
    static void findMinimumNumberOfElements(int n, int k,
                                            int[] arr)
    {
        // Sort the given array
        Array.Sort(arr);
 
        // Stores the index for the
        // array
        int index = 0;
        int count = 0;
 
        if (arr[0] > 1) {
 
            // If 1 is not present, then
            // append it
            ++count;
        }
 
        // Move on to next index
        else {
            ++index;
        }
 
        // The expected value in the array
        long expect = 2;
        while (expect <= k) {
 
            // Need to append this number
            if (index >= n || arr[index] > expect) {
                ++count;
                expect += expect;
            }
 
            // Otherwise, expand the range
            // by current number
            else {
                expect += arr[index];
                ++index;
            }
        }
 
        // Print the answer
        Console.WriteLine(count);
    }
     
    // Driver code
    public static void Main()
    {
        int[] arr = { 2, 6, 8, 12, 19 };
        int K = 20;
        int N = arr.Length;
        findMinimumNumberOfElements(N, K, arr);
    }
}
 
// This code is contributed by avijitmondal1998.
 
 

Javascript




<script>
// Javascript program for the above approach
 
// Function to find the minimum number
// of elements that must be added to
// make the sum of array element over
// the range [1, K]
function findMinimumNumberOfElements(n, k, arr) {
    // Sort the given array
    arr.sort((a, b) => a - b);
 
    // Stores the index for the
    // array
    let index = 0;
    let count = 0;
 
    if (arr[0] > 1) {
 
        // If 1 is not present, then
        // append it
        ++count;
    }
 
    // Move on to next index
    else {
        ++index;
    }
 
    // The expected value in the array
    let expect = 2;
    while (expect <= k) {
 
        // Need to append this number
        if (index >= n || arr[index] > expect) {
            ++count;
            expect += expect;
        }
 
        // Otherwise, expand the range
        // by current number
        else {
            expect += arr[index];
            ++index;
        }
    }
 
    // Print the answer
    document.write(count);
}
 
// Driver Code
 
let arr = [2, 6, 8, 12, 19];
let K = 20;
let N = arr.length;
findMinimumNumberOfElements(N, K, arr);
 
// This code is contributed by _saurabh_jaiswal.
</script>
 
 
Output: 
2

 

Time Complexity: O(max(K, N*log N))
Auxiliary Space: O(1)



Next Article
Maximize value of K such that a subsequence with sum i exists for each integer i in range [1, K]

P

parthagarwal1962000
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Mathematical
  • Sorting
  • Natural Numbers
  • subsequence
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Sorting

Similar Reads

  • Count of minimum numbers having K as the last digit required to obtain sum N
    Given a positive integer N and a digit K, the task is to find the minimum count of numbers ending with digit K such that the sum of those numbers is N. If no such number exists whose sum is K, then print "-1". Examples: Input: N = 42, K = 3Output: 4Explanation:The given number N(= 43) can be express
    7 min read
  • Minimum number of operations required to make a permutation of first N natural numbers equal
    Given an array A[] of size N, containing a permutation of first N natural numbers and an integer K, the task is to find the minimum number of operations required to make all array elements equal by selecting K (1 < K ≤ N) consecutive array elements and replacing them with the minimum of the selec
    6 min read
  • Count of elements such that difference between sum of left and right sub arrays is equal to a multiple of k
    Given an array arr[] of length n and an integer k, the task is to find the number of indices from 2 to n-1 in an array having a difference of the sum of the left and right sub arrays equal to the multiple of the given number k. Examples: Input: arr[] = {1, 2, 3, 3, 1, 1}, k = 4 Output: 2 Explanation
    7 min read
  • Minimum removal of elements from end of an array required to obtain sum K
    Given an integer K and an array A[] of size N, the task is to create a new array with sum K with minimum number of operations, where in each operation, an element can be removed either from the start or end of A[] and appended to the new array. If it is not possible to generate a new array with sum
    15+ min read
  • Maximize value of K such that a subsequence with sum i exists for each integer i in range [1, K]
    Given an array arr[] consisting of N integers, the task is to find the maximum value of K such that for every integer i over the range [1, K] there exists a subsequence whose sum is i. Examples: Input: arr[] = {1, 2, 1, 3}Output: 7Explanation:Below are the possible values of the sum for all the subs
    6 min read
  • Print all possible K-length subsequences of first N natural numbers with sum N
    Given two positive integers N and K, the task is to print all possible K-length subsequences from first N natural numbers whose sum of elements is equal to N. Examples: Input: N = 5, K = 3 Output: { {1, 1, 3}, {1, 2, 2}, {1, 3, 1}, {2, 1, 2}, {2, 2, 1}, {3, 1, 1} } Explanation: 1 + 1 + 3 = N(= 5) an
    9 min read
  • Minimum sum of medians of all possible K length subsequences of a sorted array
    Given a sorted array arr[] consisting of N integers and a positive integer K(such that N%K is 0), the task is to find the minimum sum of the medians of all possible subsequences of size K such that each element belongs to only one subsequence. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 2Output
    7 min read
  • Count of subsequences in an array with sum less than or equal to X
    Given an integer array arr[] of size N and an integer X, the task is to count the number of subsequences in that array such that its sum is less than or equal to X. Note: 1 <= N <= 1000 and 1 <= X <= 1000, where N is the size of the array. Examples: Input : arr[] = {84, 87, 73}, X = 100
    13 min read
  • Modify array to a permutation of consecutive numbers of longest length by at most K insertions
    Given an array arr[] of length N and an integer K, the task is to find the maximize the length of the array by appending at most K elements such that the array becomes a permutation of consecutive numbers starting from 1. Once K elements are added, sum of two or more array elements can be inserted.
    6 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
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