Leetcode 330: Patching Array

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.
Input: nums = [1,5,10], n = 20
Output: 2
Explanation: The two patches can be [2, 4].
Input: nums = [1,2,2], n = 5
Output: 0
class Solution {
public:
int minPatches(vector<int>& nums, int n) {
long long miss = 1;
int count = 0;
int i = 0;
while (miss <= n) {
if (i < nums.size() && nums[i] <= miss) {
miss += nums[i++];
} else {
miss += miss;
++count;
}
}

return count;
}
};

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

High Performance Logging — Java

RingZer0Team CTF SQLi challenges — Part 1

How to Solve and Create Sudoku Grids in Python

Synthetic Assets

<h1>The Road to Software Development</h1>

Reduce Cost and Increase Productivity with Value Added IT Services from buzinessware — {link} -

Do You Need to Use a Fan for Cooling with the New Raspberry Pi 4?

Implementing an Error Factory in Go

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
dume0011

dume0011

More from Medium

Leetcode Problem : 525. Contiguous Array

[Leetcode 525] Contiguous Array

Leetcode 34: Find First and Last Position of Element in Sorted Array

Linked List | LeetCode Top Interview Questions