Skip to content

2952. Minimum Number of Coins to be Added 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  // Same as 330. Patching Array
  int minimumAddedCoins(vector<int>& coins, int target) {
    int ans = 0;
    int i = 0;      // coins' index
    long miss = 1;  // the minimum sum in [1, n] we might miss

    ranges::sort(coins);

    while (miss <= target)
      if (i < coins.size() && coins[i] <= miss) {
        miss += coins[i++];
      } else {
        // Greedily add `miss` itself to increase the range from
        // [1, miss) to [1, 2 * miss).
        miss += miss;
        ++ans;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  // Same as 330. Patching Array
  public int minimumAddedCoins(int[] coins, int target) {
    int ans = 0;
    int i = 0;     // coins' index
    long miss = 1; // the minimum sum in [1, n] we might miss

    Arrays.sort(coins);

    while (miss <= target)
      if (i < coins.length && coins[i] <= miss) {
        miss += coins[i++];
      } else {
        // Greedily add `miss` itself to increase the range from
        // [1, miss) to [1, 2 * miss).
        miss += miss;
        ++ans;
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  # Same as 330. Patching Array
  def minimumAddedCoins(self, coins: list[int], target: int) -> int:
    ans = 0
    i = 0  # coins' index
    miss = 1  # the minimum sum in [1, n] we might miss

    coins.sort()

    while miss <= target:
      if i < len(coins) and coins[i] <= miss:
        miss += coins[i]
        i += 1
      else:
        # Greedily add `miss` itself to increase the range from
        # [1, miss) to [1, 2 * miss).
        miss += miss
        ans += 1

    return ans