數組最大子序列和
這個問題可以使用動態規劃來解決,稱為「Kadane's algorithm」。以下是Python的實現:
def max_subarray_sum(arr):
if not arr:
return 0
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
max_global = max_current
return max_global
這個函數接受一個整數列表作為輸入,並返回該列表中最大的子序列和。它通過遍歷列表中的每個元素,保持兩個變量:max_current
(當前子序列的最大和)和max_global
(迄今為止找到的最大子序列和)。對於列表中的每一個新元素,我們都更新max_current
,使其成為當前數字或與前一個子序列和相加的較大值。如果max_current
變得比max_global
更大,則更新max_global
。
例如:
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(max_subarray_sum(arr)) # Output: 6 (子序列 [4, -1, 2, 1])
這個函數的時間複雜度為O(n),其中n是列表的長度,因為我們只遍歷列表一次。