Minimum Elements

Given an array of positive integers and a target sum, return the minimum number of elements needed to form exactly that sum using unlimited copies of the array elements. Return -1 if the sum cannot be formed. This is an unbounded-choice minimization DP.

Input Format

nums = allowed values, x = target sum

Output Format

minimum number of elements needed, or -1

Constraints

  • 1 <= nums.length <= 20; 1 <= nums[i] <= 1000; 0 <= x <= 10^4

Examples

Example 1:

Input:

nums = [1,4,5]
x = 8

Output:

2

Explanation:

8 = 4 + 4.

Example 2:

Input:

nums = [4,6]
x = 7

Output:

2

Explanation:

7 cannot be formed using 4 and 6.

Loading...
Minimum Elements - Dp Knapsack DSA Problem