[LeetCode] Patching Array

Source: Internet
Author: User

[LeetCode] Patching Array

Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range[1, n]Specified sive can be formed by the sum of some elements in the array. Return the minimum number of patches required.

Example 1:
Nums =[1, 3], N = 6
Return 1.

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:
Nums =[1, 5, 10], N = 20
Return 2.
The two patches can be[2, 4].

Example 3:
Nums =[1, 2, 2], N = 5
Return 0.

Solutions

Suppose the range that the array can currently represent is[1, total)To add elements to the array.addExtend the representation range[1, total + add), Whereadd≤total. When and only whenadd=totalMaximum time range[1, 2 * total).

When the array contains less than or equal addThe elements in the array are used. If no, add a new element. add. Implementation Code
//Runtime: 1 mspublic class Solution {    public int minPatches(int[] nums, int n) {        long miss = 1;        int add = 0;        int i = 0;        while (miss <= n) {            if (i < nums.length && nums[i] <= miss){                miss += nums[i++];            } else {                miss += miss;                add += 1;            }        }        return add;    }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.