![]() |
VOOZH | about |
Given an integer V and an array arr[] consisting of N integers, the task is to find the maximum number of array elements that can be selected from array arr[] to obtain the sum V. Each array element can be chosen any number of times. If the sum cannot be obtained, print -1.
Examples:
Input: arr[] = {25, 10, 5}, V = 30
Output: 6
Explanation:
To obtain sum 30, select arr[2] (= 5), 6 times.
Therefore, the count is 6.Input: arr[] = {9, 6, 4, 3}, V = 11
Output: 3
Explanation:
To obtain sum 11, possible combinations is : 4,4,3
Therefore, the count is 3
Naive Approach: The simplest approach is to recursively find the maximum number of array elements to generate the sum V using array elements from indices 0 to j before finding the maximum number of elements required to generate V using elements from indices 0 to i where j < i < N. After completing the above steps, print the count of array elements required to obtain the given sum V.
Time Complexity: O(VN)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Follow the below steps to solve the problem:
table[i] = Max(table[i - arr[j]], table[i]), Where table[i-arr[j]]!=-1
where 1 ? i ? V and 0 ? j ? N
Below is the implementation of the above approach:
6
Time Complexity: O(N * V)
Auxiliary Space: O(N)