[greedy algorithm] complete the array as required

Time:2020-11-24

[greedy algorithm] complete the array as required

Nums is a positive array of integers and integers. Select any number from the [1, n] interval and add it to nums, so that any number in [1, n] interval can be represented by the sum of some numbers in nums. Please output the minimum number of digits that meet the above requirements.

Example 1:

Input: nums = [1,3], n = 6
Output: 1 
Explanation:
According to the existing combinations [1], [3], [1,3] in nums, we can get 1,3,4.
Now if we add 2 to nums, the combination becomes: [1], [2], [3], [1,3], [2,3], [1,2,3].
The sum can represent the numbers 1, 2, 3, 4, 5, 6, and cover all the numbers in the interval [1, 6].
So we need to add at least one number.

Example 2:

Input: nums = [1,5,10], n = 20
Output: 2
Explanation: we need to add [2,4].

Example 3:

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

Leetcode topic address

JavaScript

/**
 * @param {number[]} nums
 * @param {number} n
 * @return {number}
 */
var minPatches = function (nums, n) {
    var patches = 0, i = 0;
    var miss = 1;
    while (miss <= n) {
        if (i < nums.length && nums[i] <= miss) {
            miss += nums[i++];
            console.log(miss)
        } else {
            miss += miss;
            patches++;
        }
    }
    return patches;
};

Python

from typing import List
class Solution:
    def minPatches(self, nums: List[int], n: int) -> int:
        patches,i,miss = 0,0,1
        while miss <= n:
            if i < len(nums) and nums[i] <= miss: 
                miss += nums[i]
                i +=1
            else:
                miss += miss
                patches += 1
        return patches

Recommended Today

SDS of redis data structure

SDS(simple dynamic string), simple dynamic string. S and it’s called hacking string. Where hack is stored is the length of the string and the remaining space in SDS. The implementation of SDS insds.cIn the middle. C language string uses a character array of length N + 1 to represent the string of length N, and […]