From N! to N^2 (Dynamic Programming) - Part II
I tried this problem using brute-force but it was clear that it wouldn't work with an input of num=3000. Complexity for the brute-force was 3000 factorial.
Instead, this was a problem similar to counting coins or solving Diophantine equations: if you manage to have all the solutions from 0..num-1, you can find the solution for num. Notice that the solution for num will require an extra loop from i=1..num where you're going to compare the current solution for num dp[num] to all solutions dp[num-i], assuming that i ends with the digit k. The two loops together lead to an num^2 solution, which runs very quick given the small num. Solution is down below, Merci, ACC.
Sum of Numbers With Units Digit K - LeetCode
Given two integers num
and k
, consider a set of positive integers with the following properties:
- The units digit of each integer is
k
. - The sum of the integers is
num
.
Return the minimum possible size of such a set, or -1
if no such set exists.
Note:
- The set can contain multiple instances of the same integer, and the sum of an empty set is considered
0
. - The units digit of a number is the rightmost digit of the number.
Example 1:
Input: num = 58, k = 9 Output: 2 Explanation: One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9. Another valid set is [19,39]. It can be shown that 2 is the minimum possible size of a valid set.
Example 2:
Input: num = 37, k = 2 Output: -1 Explanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.
Example 3:
Input: num = 0, k = 7 Output: 0 Explanation: The sum of an empty set is considered 0.
Constraints:
0 <= num <= 3000
0 <= k <= 9
public int MinimumNumbers(int num, int k) { int[] dp = new int[num + 1]; dp[0] = 0; for (int i = 1; i < dp.Length; i++) dp[i] = -1; for (int i = 1; i <= num; i++) { for (int j = 1; j <= i; j++) { if (j % 10 == k && dp[i - j] != -1) { dp[i] = (dp[i] == -1) ? dp[i - j] + 1 : Math.Min(dp[i], dp[i - j] + 1); } } } return dp[num]; }
Comments
Post a Comment