贪心维护当前数字可覆盖区域, \(r\)表示\([1, r - 1]\)区间被覆盖
对于当前\(num[i]\), 如果\(num[i] \le r\), 维护\(r = r + num[i]\)
否则当前最优填入数字为\(r\), 可以将区间扩展为\([1, 2\times r - 1]\), 即\(r = 2\times r\)
class Solution:
def minPatches(self, nums: List[int], n: int) -> int:
r, l, i, ans = 1, len(nums), 0, 0
while r <= n:
if i < l and nums[i] <= r:
r, i = r + nums[i], i + 1
else:
r, ans = r * 2, ans + 1
return ans