我在https://www.hackerrank.com/challenges/angry-children處玩弄一個問題。我已經編寫了正確解決一些測試用例的解決方案。其他測試用例,提供更多輸入,超時的情況。我如何更改此代碼以更快處理?更高效的Python 3
N = int(input())
K = int(input())
D = K - 1
N_set = []
for n in range(N):
N_set.append(int(input()))
N_set.sort(reverse=True)
#Find differences between each integer in the list
D_set = []
for d in range(0,N-1):
D_set.append(N_set[d]-N_set[d+1])
D_Start = 0
D_End = D
min_summed_diff = 99999999999999
D_Start_Hold = None
D_End_Hold = None
count_down = len(D_set) - D + 1
while count_down:
#print(count_down)
temp_summed_diff = 0
for i in range(D_Start, D_End):
temp_summed_diff += D_set[i]
if temp_summed_diff < min_summed_diff:
min_summed_diff = temp_summed_diff
D_Start_Hold = D_Start
D_End_Hold = D_End
D_Start += 1
D_End += 1
count_down -= 1
K_set = N_set[D_Start_Hold:D_End_Hold+1]
unfairness = max(K_set) - min(K_set)
print(unfairness)
運行一下,看看伸出? – Kevin 2015-03-13 20:09:32