|
3 | 3 | import java.util.ArrayList;
|
4 | 4 | import java.util.List;
|
5 | 5 |
|
6 |
| -/** |
7 |
| - * 330. Patching Array |
8 |
| - * |
9 |
| - * Given a sorted positive integer array nums and an integer n, |
10 |
| - * add/patch elements to the array such that any number in range [1, n] |
11 |
| - * inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required. |
12 |
| -
|
13 |
| - Example 1: |
14 |
| - nums = [1, 3], n = 6 |
15 |
| - Return 1. |
16 |
| -
|
17 |
| - Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4. |
18 |
| - Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3]. |
19 |
| - Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. |
20 |
| - So we only need 1 patch. |
21 |
| -
|
22 |
| - Example 2: |
23 |
| - nums = [1, 5, 10], n = 20 |
24 |
| - Return 2. |
25 |
| - The two patches can be [2, 4]. |
26 |
| -
|
27 |
| - Example 3: |
28 |
| - nums = [1, 2, 2], n = 5 |
29 |
| - Return 0. |
30 |
| - */ |
31 | 6 | public class _330 {
|
32 | 7 |
|
33 | 8 | public static class Solution1 {
|
34 | 9 | /**
|
35 | 10 | * credit: https://leetcode.com/articles/patching-array/ and https://discuss.leetcode.com/topic/35494/solution-explanation/2
|
36 |
| - * |
| 11 | + * <p> |
37 | 12 | * Let miss be the smallest sum in [0,n] that we might be missing. Meaning we already know we
|
38 | 13 | * can build all sums in [0,miss). Then if we have a number num <= miss in the given array, we
|
39 | 14 | * can add it to those smaller sums to build all sums in [0,miss+num). If we don't, then we must
|
40 | 15 | * add such a number to the array, and it's best to add miss itself, to maximize the reach.
|
41 |
| - * |
| 16 | + * <p> |
42 | 17 | * Example: Let's say the input is nums = [1, 2, 4, 13, 43] and n = 100. We need to ensure that
|
43 | 18 | * all sums in the range [1,100] are possible. Using the given numbers 1, 2 and 4, we can
|
44 | 19 | * already build all sums from 0 to 7, i.e., the range [0,8). But we can't build the sum 8, and
|
|
0 commit comments