累加出整個範圍所有的數最少還需要幾個數

2021-09-26 08:19:02 字數 597 閱讀 1278

題目:給定乙個有序的正數陣列arr和乙個正數range,如果可以自由選擇arr中的數字,想累加得到1~range範圍上所有的數,返回arr最少還缺幾個數

舉例:arr = [1,2,3,7]  range = 15  1~15還缺14 返回1

arr = [1,5,7] range = 15 1~15還缺2和4 返回2

def needmins(arr,range_):

range = 0

needs = 0

for i in range(len(arr)):

if arr[i] > range + 1:

range = 2 * range + 1

needs += 1

if range > range_:

return needs

range += arr[i]

if range > range_:

return needs

while range_ > range + 1:

range = 2 * range + 1

needs += 1

return needs