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 <= nums[i] <= 10^4 1<=nums[i]<=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;
}
相关推荐
小范自学编程14 小时前
算法训练营 Day38 - 动态规划part07
算法·动态规划
自动化和Linux14 小时前
C语言_scanf(),strlen(),size()的特性和各自的区别
c语言·开发语言
小郝 小郝14 小时前
51 与32 单片机LED控制详解
c语言·开发语言·经验分享·学习·51单片机
星空露珠14 小时前
迷你世界UGC3.0脚本Wiki全局函数
开发语言·数据库·算法·游戏·lua
小王不爱笑13214 小时前
排序算法 Java
数据结构·算法·排序算法
无敌憨憨大王15 小时前
二叉树的最短路径长度(BFS+DFS)
算法·深度优先·宽度优先
tankeven15 小时前
HJ132 小红走网格
c++·算法
小璐资源网15 小时前
算法黑箱的可解释性危机
算法
不想看见40415 小时前
Power of Four二进制特性--力扣101算法题解笔记
数据结构·算法
做怪小疯子15 小时前
Leetcode刷题——8.重叠区间
算法·leetcode·职场和发展