Given an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.
Examples: 
Input: X = 7, arr[] = {3, 5, 4}
Output: 2
The minimum number elements will be 2 as
3 and 4 can be selected to reach 7.Input: X = 4, arr[] = {5}
Output: -1
Approach: We have already seen how to solve this problem using dynamic-programming approach in this article.
Here, we will see a slightly different approach to solve this problem using BFS. 
Before that, let’s go ahead and define a state. A state SX can be defined as the minimum number of integers we would need to take from array to get a total of X.
Now, if we start looking at each state as a node in a graph such that each node is connected to (SX – arr[0], SX – arr[1], … SX – arr[N – 1]). 
Thus, we have to find the shortest path from state N to 0 in an unweighted and this can be done using BFS. BFS works here because the graph is unweighted.
Below is the implementation of the above approach: 
C++
| // C++ implementation of the approach#include <bits/stdc++.h>usingnamespacestd;// Function to find the minimum number// of integers requiredintminNumbers(intx, int* arr, intn){    // Queue for BFS    queue<int> q;    // Base value in queue    q.push(x);    // Boolean array to check if a number has been    // visited before    unordered_set<int> v;    // Variable to store depth of BFS    intd = 0;    // BFS algorithm    while(q.size()) {        // Size of queue        ints = q.size();        while(s--) {            // Front most element of the queue            intc = q.front();            // Base case            if(!c)                returnd;            q.pop();            if(v.find(c) != v.end() or c < 0)                continue;            // Setting current state as visited            v.insert(c);            // Pushing the required states in queue            for(inti = 0; i < n; i++)                q.push(c - arr[i]);        }        d++;    }    // If no possible solution    return-1;}// Driver codeintmain(){    intarr[] = { 3, 3, 4 };    intn = sizeof(arr) / sizeof(int);    intx = 7;    cout << minNumbers(x, arr, n);    return0;} | 
Java
| // Java implementation of the approachimportjava.util.*;classGFG{// Function to find the minimum number// of integers requiredstaticintminNumbers(intx, int[]arr, intn){    // Queue for BFS    Queue<Integer> q = newLinkedList<>();    // Base value in queue    q.add(x);    // Boolean array to check if     // a number has been visited before    HashSet<Integer> v = newHashSet<Integer>();    // Variable to store depth of BFS    intd = 0;    // BFS algorithm    while(q.size() > 0)     {        // Size of queue        ints = q.size();        while(s-- > 0)        {            // Front most element of the queue            intc = q.peek();            // Base case            if(c == 0)                returnd;            q.remove();            if(v.contains(c) || c < 0)                continue;            // Setting current state as visited            v.add(c);            // Pushing the required states in queue            for(inti = 0; i < n; i++)                q.add(c - arr[i]);        }        d++;    }    // If no possible solution    return-1;}// Driver codepublicstaticvoidmain(String[] args){    intarr[] = { 3, 3, 4};    intn = arr.length;    intx = 7;    System.out.println(minNumbers(x, arr, n));}}// This code is contributed by Rajput-Ji | 
Python3
| # Python3 implementation of the approach # Function to find the minimum number # of integers required defminNumbers(x, arr, n) :     q =[]     # Base value in queue     q.append(x)     v =set([])     d =0    while(len(q) > 0) :         s =len(q)         while(s) :             s -=1            c =q[0]             #print(q)            if(c ==0) :                 returnd             q.pop(0)             if((c inv) orc < 0) :                continue            # Setting current state as visited             v.add(c)             # Pushing the required states in queue             fori inrange(n) :                 q.append(c -arr[i])                                 d +=1        #print()        #print(d,c)    # If no possible solution     return-1arr =[ 1, 4,6]n =len(arr)x =20print(minNumbers(x, arr, n))# This code is contributed by divyeshrabadiya07# Improved by nishant.k108 | 
C#
| // C# implementation of the approachusingSystem;usingSystem.Collections.Generic;     classGFG{// Function to find the minimum number// of integers requiredstaticintminNumbers(intx, int[]arr, intn){    // Queue for BFS    Queue<int> q = newQueue<int>();    // Base value in queue    q.Enqueue(x);    // Boolean array to check if     // a number has been visited before    HashSet<int> v = newHashSet<int>();    // Variable to store depth of BFS    intd = 0;    // BFS algorithm    while(q.Count > 0)     {        // Size of queue        ints = q.Count;        while(s-- > 0)        {            // Front most element of the queue            intc = q.Peek();            // Base case            if(c == 0)                returnd;            q.Dequeue();            if(v.Contains(c) || c < 0)                continue;            // Setting current state as visited            v.Add(c);            // Pushing the required states in queue            for(inti = 0; i < n; i++)                q.Enqueue(c - arr[i]);        }        d++;    }    // If no possible solution    return-1;}// Driver codepublicstaticvoidMain(String[] args){    int[]arr = { 3, 3, 4 };    intn = arr.Length;    intx = 7;    Console.WriteLine(minNumbers(x, arr, n));}}// This code is contributed by Rajput-Ji | 
Javascript
| <script>// Javascript implementation of the approach// Function to find the minimum number// of integers requiredfunctionminNumbers(x, arr, n){    // Queue for BFS    varq = [];    // Base value in queue    q.push(x);    // Boolean array to check if a number has been    // visited before    varv = newSet();    // Variable to store depth of BFS    vard = 0;    // BFS algorithm    while(q.length!=0) {        // Size of queue        vars = q.length;        while(s--) {            // Front most element of the queue            varc = q[0];            // Base case            if(!c)                returnd;            q.shift();            if(v.has(c) || c < 0)                continue;            // Setting current state as visited            v.add(c);            // Pushing the required states in queue            for(vari = 0; i < n; i++)                q.push(c - arr[i]);        }        d++;    }    // If no possible solution    return-1;}// Driver codevararr = [3, 3, 4];varn = arr.length;varx = 7;document.write(minNumbers(x, arr, n));// This code is contributed by rrrtnx.</script> | 
2
Time complexity: O(N * X)
Auxiliary Space: O(N), since N extra space has been taken.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







