1
+ """
2
+ Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in
3
+ range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches
4
+ required.
5
+
6
+ Example 1:
7
+ nums = [1, 3], n = 6
8
+ Return 1.
9
+
10
+ Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
11
+ Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
12
+ Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
13
+ So we only need 1 patch.
14
+
15
+ Example 2:
16
+ nums = [1, 5, 10], n = 20
17
+ Return 2.
18
+ The two patches can be [2, 4].
19
+
20
+ Example 3:
21
+ nums = [1, 2, 2], n = 5
22
+ Return 0.
23
+ """
24
+ __author__ = 'Daniel'
25
+
26
+
27
+ class Solution (object ):
28
+ def minPatches (self , nums , n ):
29
+ """
30
+ https://discuss.leetcode.com/topic/35494/solution-explanation
31
+
32
+ Greedy
33
+ Let cur_max be the current max sum can be formed by [0, i) when iterating at i-th index
34
+ if cur_max < Ai:
35
+ we have a void gap at [cur_max + 1, Ai]
36
+ we need to patch a cur_max in the array to maximize the all-cover reach
37
+ else:
38
+ cur_max += Ai
39
+
40
+ :type nums: List[int]
41
+ :type n: int
42
+ :rtype: int
43
+ """
44
+ cnt = 0
45
+ cur_max = 0
46
+ i = 0
47
+ while cur_max < n :
48
+ if i >= len (nums ) or cur_max + 1 < nums [i ]:
49
+ cur_max += cur_max + 1
50
+ cnt += 1
51
+ else :
52
+ cur_max += nums [i ]
53
+ i += 1
54
+
55
+ return cnt
56
+
57
+ def minPatches2 (self , nums , n ):
58
+ """
59
+ https://discuss.leetcode.com/topic/35494/solution-explanation
60
+
61
+ Greedy
62
+ Let cur_max be the current max sum can be formed by [0, i) when iterating at i-th index
63
+ if cur_max < Ai:
64
+ we have a void gap at [cur_max + 1, Ai]
65
+ we need to patch a cur_max in the array to maximize the all-cover reach
66
+ else:
67
+ cur_max += Ai
68
+
69
+ :type nums: List[int]
70
+ :type n: int
71
+ :rtype: int
72
+ """
73
+ nums = filter (lambda x : x <= n , nums )
74
+
75
+ cnt = 0
76
+ cur_max = 0
77
+ for elt in nums :
78
+ while cur_max + 1 < elt :
79
+ cur_max += cur_max + 1
80
+ cnt += 1
81
+
82
+ cur_max += elt
83
+
84
+ # after iterating all array element
85
+ while cur_max < n :
86
+ cur_max += cur_max + 1
87
+ cnt += 1
88
+
89
+ return cnt
90
+
91
+
92
+ if __name__ == "__main__" :
93
+ assert Solution ().minPatches ([1 , 2 , 2 , 6 , 34 ], 20 ) == 1
0 commit comments