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;
}
相关推荐
繁依Fanyi12 分钟前
简易安卓句分器实现
java·服务器·开发语言·算法·eclipse
烦躁的大鼻嘎28 分钟前
模拟算法实例讲解:从理论到实践的编程之旅
数据结构·c++·算法·leetcode
IU宝31 分钟前
C/C++内存管理
java·c语言·c++
qq_4597300335 分钟前
C 语言面向对象
c语言·开发语言
C++忠实粉丝1 小时前
计算机网络socket编程(4)_TCP socket API 详解
网络·数据结构·c++·网络协议·tcp/ip·计算机网络·算法
祁思妙想1 小时前
10.《滑动窗口篇》---②长度最小的子数组(中等)
leetcode·哈希算法
用户37791362947551 小时前
【循环神经网络】只会Python,也能让AI写出周杰伦风格的歌词
人工智能·算法
福大大架构师每日一题1 小时前
文心一言 VS 讯飞星火 VS chatgpt (396)-- 算法导论25.2 1题
算法·文心一言
EterNity_TiMe_1 小时前
【论文复现】(CLIP)文本也能和图像配对
python·学习·算法·性能优化·数据分析·clip
陌小呆^O^2 小时前
Cmakelist.txt之win-c-udp-client
c语言·开发语言·udp