[LeetCode] 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.

  • Record : 27min 6sec
  • Space : O(1)
  • Time : O(N)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int minPatches(vector<int>& nums, int n) {
long tot = 0, res = 0;
for(int i = 0; i < nums.size() && tot < n && nums[i] <= n; i++) {
while(tot + 1 < nums[i]) {
tot = tot + tot + 1;
res++;
}
tot += nums[i];
}
while(tot < n) {
tot = tot + tot + 1;
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/02/PS/LeetCode/patching-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.