Algorithm: Leetcode Contest 372
2952. Minimum Number of Coins to be Added
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 the minimum number of coins of any value that need to be added to the array so that every integer in the range [1, target]
is obtainable.
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.
Solution
public int minimumAddedCoins(int[] coins, int target) {
Arrays.sort(coins);
long curRange = 0;
int res = 0;
for(int coin: coins) {
while(curRange + 1 < coin) {
res++;
curRange += curRange + 1;
}
curRange += coin;
}
while(curRange < target) {
curRange += curRange + 1;
res++;
}
return res;
}
Retrospect
this is a typical problem called the minimum uncomposable sum.
I remember the solution I came up is permuting all coins, get the possible sum, then count how many gaps there are.
Seems I am not familiar with this classic problem so didn’t figure out the right solution.
another two problem is so hard for me… :(