大半夜不睡覺做出來的題,一定不能浪費,記錄下來,人真是老了,肯定有優化空間,但是現在不想想了,大家如果有優化的地方歡迎在評論留言,我一定改進。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
input = [13,-3,-25,20,-3,-16,-18,18,20,-7,12,-5,-22,15,-4,7]
def fast(input):
# 記錄最大的子數組的和
max = 0
# 記錄除了最大子數組的右腳標到i所在位置的數字和
temp = 0
# 記錄temp中的到當前腳標i所在位置的最大子數組
other_temp = 0
# 記錄other_temp的左腳標
start_tmp = 1
# 記錄最大子數組的左腳標
start = 0
# 記錄最大子數組的右腳標
end = 0
i = 0
while i < len(input):
if input[i] > 0:
# 如果當前位置元素大於max,則直接從當前位置開始
if input[i] > max:
max = input[i]
start = i
end = i
temp = 0
other_temp = 0
elif input[i] + temp > 0:
# 如果當前元素加上中間所有臨時元素再加上當前最大子數組和小於當前元素加上臨時元素的最大子數組,則拋棄max而使用other_temp
if input[i] + temp + max < input[i] + other_temp:
max = other_temp + input[i]
start = start_tmp
# 反之則將start到end的所有元素作爲最大子數組
else:
max = max + temp + input[i]
temp = 0
other_temp = 0
end = i
else:
temp = temp + input[i]
other_temp = other_temp + input[i]
# 如果臨時數組中的最大子數組已經大於max,則使用other_temp
if other_temp > max:
max = other_temp
start = start_tmp
temp = 0
other_temp = 0
else:
temp = temp + input[i]
other_temp = other_temp + input[i]
# 如果temp+max已經小於0且當前元素<0,則臨時數組沒有意義,臨時數組的腳標至少要從下個元素開始纔有意義
if temp + max < 0:
other_temp = 0
start_tmp = i+1
i = i+1
print(max, start, end)
# 輸出(43, 7, 10)