330. Patching Array Hard
1/**
2 * [330] Patching Array
3 *
4 * Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.
5 * Return the minimum number of patches required.
6 *
7 * Example 1:
8 *
9 * Input: nums = [1,3], n = 6
10 * Output: 1
11 * Explanation:
12 * Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
13 * Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
14 * Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
15 * So we only need 1 patch.
16 *
17 * Example 2:
18 *
19 * Input: nums = [1,5,10], n = 20
20 * Output: 2
21 * Explanation: The two patches can be [2, 4].
22 *
23 * Example 3:
24 *
25 * Input: nums = [1,2,2], n = 5
26 * Output: 0
27 *
28 *
29 * Constraints:
30 *
31 * 1 <= nums.length <= 1000
32 * 1 <= nums[i] <= 10^4
33 * nums is sorted in ascending order.
34 * 1 <= n <= 2^31 - 1
35 *
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/patching-array/
40// discuss: https://leetcode.com/problems/patching-array/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45 pub fn min_patches(nums: Vec<i32>, n: i32) -> i32 {
46 0
47 }
48}
49
50// submission codes end
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn test_330() {
58 }
59}
60
Back
© 2025 bowen.ge All Rights Reserved.