LeetCode //C - 330. Patching Array

330. Patching Array

Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range 1, n inclusive can be formed by the sum of some elements in the array.

Return the minimum number of patches required.

Example 1:

Input: nums = 1,3, n = 6
Output: 1
Explanation:

Combinations of nums are 1, 3, 1,3, which form possible sums of: 1, 3, 4.

Now if we add/patch 2 to nums, the combinations are: 1, 2, 3, 1,3, 2,3, 1,2,3.

Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range 1, 6.

So we only need 1 patch.

Example 2:

Input: nums = 1,5,10, n = 20
Output: 2
Explanation: The two patches can be 2, 4.

Example 3:

Input: nums = 1,2,2, n = 5
Output: 0

Constraints:
  • 1 <= nums.length <= 1000
  • 1 < = n u m s i < = 1 0 4 1 <= numsi <= 10^4 1<=numsi<=104
  • nums is sorted in ascending order.
  • 1 < = n < = 2 31 − 1 1 <= n <= 2^{31} - 1 1<=n<=231−1

From: LeetCode

Link: 330. Patching Array


Solution:

Ideas:
  • miss: This variable represents the smallest sum that cannot be achieved with the current elements of the array.
  • i: This is the index to traverse the array nums.
  • patches: This is the counter for the number of patches needed.
Code:
c 复制代码
int minPatches(int* nums, int numsSize, int n) {
    long long miss = 1;  // The smallest sum that we cannot achieve yet
    int i = 0, patches = 0;
    
    while (miss <= n) {
        if (i < numsSize && nums[i] <= miss) {
            miss += nums[i];
            i++;
        } else {
            miss += miss;
            patches++;
        }
    }
    
    return patches;
}
相关推荐
qizayaoshuap18 分钟前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
皓月斯语1 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet1 小时前
树状结构在查询优化中的作用与实现细节7
算法
徐凤年_2 小时前
rog_map参数理解
算法
春日见2 小时前
算法与数据结构----哈希表
数据结构·人工智能·算法·机器学习·自动驾驶·哈希算法·散列表
叩码以求索2 小时前
统计按位或能得到最大值的子集数目(一)
数据结构·算法
tachibana23 小时前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
txzrxz3 小时前
单调队列讲解
数据结构·c++·算法·单调队列
blevoice4 小时前
抖抖燃脂机单 AC6966B 主控调试踩坑:Type-C 整机供电喇叭无声排障
c语言·开发语言·单片机
不会就选b4 小时前
算法日常・每日刷题--<快排>4
算法