You are given a 0-indexed integer array coins, representing the values of the coins available, and an integer target.
An integer x is obtainable if there exists a subsequence of coins that sums to x.
Return theminimum number of coins of any value that need to be added to the array so that every integer in the range[1, target]isobtainable.
A subsequence of an array is a new non-empty array that is formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements.
Input: coins =[1,4,10], target =19Output: 2Explanation: We need to add coins 2 and 8. The resulting array will be [1,2,4,8,10].It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 2is the minimum number of coins that need to be added to the array.
Input: coins =[1,4,10,5,7,19], target =19Output: 1Explanation: We only need to add the coin 2. The resulting array will be [1,2,4,5,7,10,19].It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 1is the minimum number of coins that need to be added to the array.
Input: coins =[1,1,1], target =20Output: 3Explanation: We need to add coins 4,8, and 16. The resulting array will be [1,1,1,4,8,16].It can be shown that all integers from 1 to 20 are obtainable from the resulting array, and that 3is the minimum number of coins that need to be added to the array.
To cover every sum from 1 to target, always add the smallest value that cannot be formed yet. This greedy approach ensures minimal additions, as each new coin extends the range of obtainable sums maximally.
classSolution {
publicintminimumAddedCoins(int[] coins, int target) {
Arrays.sort(coins);
long miss = 1;
int i = 0, added = 0;
while (miss <= target) {
if (i < coins.length&& coins[i]<= miss) {
miss += coins[i++];
} else {
miss += miss;
added++;
}
}
return added;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funminimumAddedCoins(coins: IntArray, target: Int): Int {
coins.sort()
var miss = 1Lvar i = 0var added = 0while (miss <= target) {
if (i < coins.size && coins[i] <= miss) {
miss += coins[i]
i++ } else {
miss += miss
added++ }
}
return added
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defminimumAddedCoins(self, coins: list[int], target: int) -> int:
coins.sort()
miss: int =1 i: int =0 added: int =0while miss <= target:
if i < len(coins) and coins[i] <= miss:
miss += coins[i]
i +=1else:
miss += miss
added +=1return added
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnminimum_added_coins(mut coins: Vec<i32>, target: i32) -> i32 {
coins.sort();
letmut miss =1;
letmut i =0;
letmut added =0;
while miss <= target {
if i < coins.len() && coins[i] <= miss {
miss += coins[i];
i +=1;
} else {
miss += miss;
added +=1;
}
}
added
}
}