Minimum count of numbers required from given array to represent S
Last Updated :
27 Dec, 2023
Given an integer S and an array arr[], the task is to find the minimum number of elements whose sum is S, such that any element of the array can be chosen any number of times to get sum S.
Examples:
Input: arr[] = {25, 10, 5}, S = 30
Output: 2
Explanation:
In the given array there are many possible solutions such as -
5 + 5 + 5 + 5 + 5 + 5 = 30, or
10 + 10 + 10 = 30, or
25 + 5 = 30
Hence, the minimum possible solution is 2
Input: arr[] = {2, 1, 4, 3, 5, 6}, Sum= 6
Output: 1
Explanation:
In the given array there are many possible solutions such as -
2 + 2 + 2 = 6, or
2 + 4 = 6, or
6 = 6,
Hence, the minimum possible solution is 1
Approach:
The idea is to find every possible sequence recursively such that their sum is equal to the given S and also keep track of the minimum sequence such that their sum is given S. In this way, the minimum possible solution can be calculated easily.
Below is the implementation of the above approach:
C++
// C++ implementation to find the
// minimum number of sequence
// required from array such that
// their sum is equal to given S
#include <bits/stdc++.h>
using namespace std;
// Function to find the
// minimum elements required to
// get the sum of given value S
int printAllSubsetsRec(int arr[],
int n,
vector<int> v,
int sum)
{
// Condition if the
// sequence is found
if (sum == 0) {
return (int)v.size();
}
if (sum < 0)
return INT_MAX;
// Condition when no
// such sequence found
if (n == 0)
return INT_MAX;
// Calling for without choosing
// the current index value
int x = printAllSubsetsRec(
arr,
n - 1, v, sum);
// Calling for after choosing
// the current index value
v.push_back(arr[n - 1]);
int y = printAllSubsetsRec(
arr, n, v,
sum - arr[n - 1]);
return min(x, y);
}
// Function for every array
int printAllSubsets(int arr[],
int n, int sum)
{
vector<int> v;
return printAllSubsetsRec(arr, n,
v, sum);
}
// Driver Code
int main()
{
int arr[] = { 2, 1, 4, 3, 5, 6 };
int sum = 6;
int n = sizeof(arr) / sizeof(arr[0]);
cout << printAllSubsets(arr, n, sum)
<< endl;
return 0;
}
Java
// Java implementation to find the
// minimum number of sequence
// required from array such that
// their sum is equal to given S
import java.util.*;
import java.lang.*;
class GFG{
// Function to find the
// minimum elements required to
// get the sum of given value S
static int printAllSubsetsRec(int arr[],
int n,
ArrayList<Integer> v,
int sum)
{
// Condition if the
// sequence is found
if (sum == 0)
{
return (int)v.size();
}
if (sum < 0)
return Integer.MAX_VALUE;
// Condition when no
// such sequence found
if (n == 0)
return Integer.MAX_VALUE;
// Calling for without choosing
// the current index value
int x = printAllSubsetsRec(
arr,
n - 1, v, sum);
// Calling for after choosing
// the current index value
v.add(arr[n - 1]);
int y = printAllSubsetsRec(
arr, n, v,
sum - arr[n - 1]);
v.remove(v.size() - 1);
return Math.min(x, y);
}
// Function for every array
static int printAllSubsets(int arr[],
int n, int sum)
{
ArrayList<Integer> v = new ArrayList<>();
return printAllSubsetsRec(arr, n,
v, sum);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 2, 1, 4, 3, 5, 6 };
int sum = 6;
int n = arr.length;
System.out.println(printAllSubsets(arr, n, sum));
}
}
// This code is contributed by offbeat
Python3
# Python3 implementation to find the
# minimum number of sequence
# required from array such that
# their sum is equal to given S
import sys
# Function to find the
# minimum elements required to
# get the sum of given value S
def printAllSubsetsRec(arr, n, v, Sum):
# Condition if the
# sequence is found
if (Sum == 0):
return len(v)
if (Sum < 0):
return sys.maxsize
# Condition when no
# such sequence found
if (n == 0):
return sys.maxsize
# Calling for without choosing
# the current index value
x = printAllSubsetsRec(arr, n - 1, v, Sum)
# Calling for after choosing
# the current index value
v.append(arr[n - 1])
y = printAllSubsetsRec(arr, n, v,
Sum - arr[n - 1])
v.pop(len(v) - 1)
return min(x, y)
# Function for every array
def printAllSubsets(arr, n, Sum):
v = []
return printAllSubsetsRec(arr, n, v, Sum)
# Driver code
arr = [ 2, 1, 4, 3, 5, 6 ]
Sum = 6
n = len(arr)
print(printAllSubsets(arr, n, Sum))
# This code is contributed by avanitrachhadiya2155
C#
// C# implementation to find the
// minimum number of sequence
// required from array such that
// their sum is equal to given S
using System;
using System.Collections.Generic;
class GFG{
// Function to find the
// minimum elements required to
// get the sum of given value S
static int printAllSubsetsRec(int[] arr, int n,
List<int> v, int sum)
{
// Condition if the
// sequence is found
if (sum == 0)
{
return v.Count;
}
if (sum < 0)
return Int32.MaxValue;
// Condition when no
// such sequence found
if (n == 0)
return Int32.MaxValue;
// Calling for without choosing
// the current index value
int x = printAllSubsetsRec(arr, n - 1,
v, sum);
// Calling for after choosing
// the current index value
v.Add(arr[n - 1]);
int y = printAllSubsetsRec(arr, n, v,
sum - arr[n - 1]);
v.RemoveAt(v.Count - 1);
return Math.Min(x, y);
}
// Function for every array
static int printAllSubsets(int[] arr, int n,
int sum)
{
List<int> v = new List<int>();
return printAllSubsetsRec(arr, n, v, sum);
}
// Driver code
static void Main()
{
int[] arr = { 2, 1, 4, 3, 5, 6 };
int sum = 6;
int n = arr.Length;
Console.WriteLine(printAllSubsets(arr, n, sum));
}
}
// This code is contributed by divyeshrabadiya07
JavaScript
<script>
// Javascript implementation to find the
// minimum number of sequence
// required from array such that
// their sum is equal to given S
// Function to find the
// minimum elements required to
// get the sum of given value S
function prletAllSubsetsRec(arr, n, v,
sum)
{
// Condition if the
// sequence is found
if (sum == 0)
{
return v.length;
}
if (sum < 0)
return Number.MAX_VALUE;
// Condition when no
// such sequence found
if (n == 0)
return Number.MAX_VALUE;
// Calling for without choosing
// the current index value
let x = prletAllSubsetsRec(
arr,
n - 1, v, sum);
// Calling for after choosing
// the current index value
v.push(arr[n - 1]);
let y = prletAllSubsetsRec(
arr, n, v,
sum - arr[n - 1]);
v.pop(v.length - 1);
return Math.min(x, y);
}
// Function for every array
function prletAllSubsets(arr,
n, sum)
{
let v = [];
return prletAllSubsetsRec(arr, n,
v, sum);
}
// Driver Code
let arr = [ 2, 1, 4, 3, 5, 6 ];
let sum = 6;
let n = arr.length;
document.write(prletAllSubsets(arr, n, sum));
</script>
Performance Analysis:
- Time Complexity: As in the above approach, there are two choose for every number in each step which takes O(2N) time, Hence the Time Complexity will be O(2N).
- Space Complexity: As in the above approach, there is no extra space used, Hence the space complexity will be O(1).
Efficient Approach: As in the above approach there is overlapping subproblems, So the idea is to use Dynamic Programming paradigm to solve this problem. Create a DP table of N * S to store the pre-computed answer for the previous sequence that is the minimum length sequence required to get the sum as S - arr[i] and in this way the finally after calculating for every value of the array, the answer to the problem will be dp[N][S], where m is the length of the array and S is the given sum.
Below is the implementation of the above approach:
C++
// C++ implementation to find the
// minimum number of sequence
// required from array such that
// their sum is equal to given S
#include <bits/stdc++.h>
using namespace std;
// Function to find the count of
// minimum length of the sequence
int Count(int S[], int m, int n)
{
vector<vector<int> > table(
m + 1,
vector<int>(
n + 1, 0));
// Loop to initialize the array
// as infinite in the row 0
for (int i = 1; i <= n; i++) {
table[0][i] = INT_MAX - 1;
}
// Loop to find the solution
// by pre-computation for the
// sequence
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (S[i - 1] > j) {
table[i][j]
= table[i - 1][j];
}
else {
// Minimum possible
// for the previous
// minimum value
// of the sequence
table[i][j]
= min(
table[i - 1][j],
table[i][j - S[i - 1]] + 1);
}
}
}
return table[m][n];
}
// Driver Code
int main()
{
int arr[] = { 9, 6, 5, 1 };
int m = sizeof(arr) / sizeof(arr[0]);
cout << Count(arr, m, 11);
return 0;
}
Java
// Java implementation to find the
// minimum number of sequence
// required from array such that
// their sum is equal to given S
import java.util.*;
class GFG{
// Function to find the count of
// minimum length of the sequence
static int Count(int S[], int m, int n)
{
int [][]table = new int[m + 1][n + 1];
// Loop to initialize the array
// as infinite in the row 0
for(int i = 1; i <= n; i++)
{
table[0][i] = Integer.MAX_VALUE - 1;
}
// Loop to find the solution
// by pre-computation for the
// sequence
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
if (S[i - 1] > j)
{
table[i][j] = table[i - 1][j];
}
else
{
// Minimum possible for the
// previous minimum value
// of the sequence
table[i][j] = Math.min(table[i - 1][j],
table[i][j - S[i - 1]] + 1);
}
}
}
return table[m][n];
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 9, 6, 5, 1 };
int m = arr.length;
System.out.print(Count(arr, m, 11));
}
}
// This code is contributed by gauravrajput1
Python3
# Python3 implementation to find the
# minimum number of sequence
# required from array such that
# their sum is equal to given S
# Function to find the count of
# minimum length of the sequence
def Count(S, m, n):
table = [[0 for i in range(n + 1)]
for i in range(m + 1)]
# Loop to initialize the array
# as infinite in the row 0
for i in range(1, n + 1):
table[0][i] = 10**9 - 1
# Loop to find the solution
# by pre-computation for the
# sequence
for i in range(1, m + 1):
for j in range(1, n + 1):
if (S[i - 1] > j):
table[i][j] = table[i - 1][j]
else:
# Minimum possible
# for the previous
# minimum value
# of the sequence
table[i][j] = min(table[i - 1][j],
table[i][j - S[i - 1]] + 1)
return table[m][n]
# Driver Code
if __name__ == '__main__':
arr= [9, 6, 5, 1]
m = len(arr)
print(Count(arr, m, 11))
# This code is contributed by Mohit Kumar
C#
// C# implementation to find the
// minimum number of sequence
// required from array such that
// their sum is equal to given S
using System;
class GFG{
// Function to find the count of
// minimum length of the sequence
static int Count(int[] S, int m, int n)
{
int[,] table = new int[m + 1, n + 1];
// Loop to initialize the array
// as infinite in the row 0
for(int i = 1; i <= n; i++)
{
table[0, i] = int.MaxValue - 1;
}
// Loop to find the solution
// by pre-computation for the
// sequence
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
if (S[i - 1] > j)
{
table[i, j] = table[i - 1, j];
}
else
{
// Minimum possible for the
// previous minimum value
// of the sequence
table[i, j] = Math.Min(table[i - 1, j],
table[i, j - S[i - 1]] + 1);
}
}
}
return table[m, n];
}
// Driver Code
public static void Main(String[] args)
{
int[] arr = { 9, 6, 5, 1 };
int m = 4;
Console.WriteLine(Count(arr, m, 11));
}
}
// This code is contributed by jrishabh99
JavaScript
<script>
// JavaScript implementation to find the
// minimum number of sequence
// required from array such that
// their sum is equal to given S
// Function to find the count of
// minimum length of the sequence
function Count(S, m, n)
{
let table = [];
for(let i = 0;i<m+1;i++){
table[i] = [];
for(let j = 0;j<n+1;j++){
table[i][j] = 0;
}
}
// Loop to initialize the array
// as infinite in the row 0
for (let i = 1; i <= n; i++) {
table[0][i] = Number.MAX_VALUE - 1;
}
// Loop to find the solution
// by pre-computation for the
// sequence
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (S[i - 1] > j) {
table[i][j]
= table[i - 1][j];
}
else {
// Minimum possible
// for the previous
// minimum value
// of the sequence
table[i][j]
= Math.min(
table[i - 1][j],
table[i][j - S[i - 1]] + 1);
}
}
}
return table[m][n];
}
// Driver Code
let arr = [ 9, 6, 5, 1 ];
let m = arr.length;
document.write(Count(arr, m, 11));
</script>
Performance Analysis:
- Time Complexity: As in the above approach, there are two loop for the calculation of the minimum length sequence required which takes O(N2) time, Hence the Time Complexity will be O(N2).
- Space Complexity: As in the above approach, there is a extra dp table used, Hence the space complexity will be O(N2).
Efficient Approach using O(N) space only:
We can use a DP array of size (N+1). Each of the indices(i) of DP array represents the minimum number of components required to build number i.
Now, at number i, if the efficient solution uses component c, then:
numComponents(i) = numComponents(i-c) + 1
We can use this relation to fill our DP array from left to right, and can get this working in O(M*N) time with O(N) space.
C++
#include<bits/stdc++.h>
using namespace std;
int findMinCountToReachSum(int sum, vector<int> components)
{
// numWays[i] represent number of ways to build value i efficiently
// using provided components.
vector<int> numWays(sum + 1, INT_MAX - 1);
// Base case: Number of ways to make sum 0 is 0.
numWays[0] = 0;
for (int i = 1; i <= sum; i++)
{
// Try to improve the value using given components.
for (int j = 0; j < components.size(); j++)
{
// component c can only contribute to building number i if it is
// less than or equal to number i.
if (i >= components[j])
{
// Check if component c can be utilized to build number i in
// a better way.
numWays[i] = min(numWays[i], numWays[i - components[j]] + 1);
}
}
}
return (numWays[sum] == INT_MAX - 1) ? -1 : numWays[sum];
}
int main()
{
int sum = 6;
vector<int> arr = {2,1,4,3,5,6};
cout << findMinCountToReachSum(sum, arr);
return 0;
}
Java
import java.util.Arrays;
public class MinCountToReachSum {
static int findMinCountToReachSum(int sum, int[] components) {
int[] numWays = new int[sum + 1];
Arrays.fill(numWays, Integer.MAX_VALUE - 1);
// Base case: Number of ways to make sum 0 is 0.
numWays[0] = 0;
for (int i = 1; i <= sum; i++) {
// Try to improve the value using given components.
for (int j = 0; j < components.length; j++) {
// component c can only contribute to building number i if it is
// less than or equal to number i.
if (i >= components[j]) {
// Check if component c can be utilized to build number i in
// a better way.
numWays[i] = Math.min(numWays[i], numWays[i - components[j]] + 1);
}
}
}
return (numWays[sum] == Integer.MAX_VALUE - 1) ? -1 : numWays[sum];
}
public static void main(String[] args) {
int sum = 6;
int[] arr = {2,1,4,3,5,6};
System.out.println(findMinCountToReachSum(sum, arr));
}
}
Python3
def find_min_count_to_reach_sum(sum, components):
num_ways = [float('inf')] * (sum + 1)
num_ways[0] = 0
for i in range(1, sum + 1):
for j in range(len(components)):
if i >= components[j]:
num_ways[i] = min(num_ways[i], num_ways[i - components[j]] + 1)
return -1 if num_ways[sum] == float('inf') else num_ways[sum]
# Example usage
sum_value = 6
components_arr = [2,1,4,3,5,6]
result = find_min_count_to_reach_sum(sum_value, components_arr)
print(result)
C#
using System;
class Program
{
static int FindMinCountToReachSum(int sum, int[] components)
{
int[] numWays = new int[sum + 1];
for (int i = 1; i <= sum; i++)
{
numWays[i] = int.MaxValue; // Start with an invalid value.
// Try to improve the value using given components.
foreach (int component in components)
{
// A component can only contribute if it is less than or equal to the target value.
if (i >= component && numWays[i - component] != int.MaxValue)
{
// Check if the component can be utilized to build the target value in a better way.
numWays[i] = Math.Min(numWays[i], numWays[i - component] + 1);
}
}
}
return numWays[sum] == int.MaxValue ? -1 : numWays[sum];
}
static void Main()
{
int sum = 6;
int[] arr = {2,1,4,3,5,6 };
int result = FindMinCountToReachSum(sum, arr);
Console.WriteLine(result);
}
}
JavaScript
function findMinCountToReachSum(sum, components) {
const numWays = new Array(sum + 1).fill(Number.MAX_SAFE_INTEGER);
numWays[0] = 0;
for (let i = components[0]; i <= sum; i++) {
for (let j = 0; j < components.length; j++) {
if (i >= components[j]) {
numWays[i] = Math.min(numWays[i], numWays[i - components[j]] + 1);
}
}
}
return numWays[sum] === Number.MAX_SAFE_INTEGER ? -1 : numWays[sum];
}
// Example usage
const sum = 6;
const arr = [2,1,4,3,5,6];
const result = findMinCountToReachSum(sum, arr);
console.log(result);
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read