python求最大连续子数组
生活随笔
收集整理的這篇文章主要介紹了
python求最大连续子数组
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
尋找最大子數組問題:
給定數組A:尋找A中的和最大的非空連續子數組。我們稱這樣的連續子數組為最大子數組(maximum subarray)
1、暴力求解:兩個循環,時間復雜度為O(n^2)
2、用分治策略的求解方法:
假定我們要尋找子數組A[low...high]的最大子數組。使用分治技術意味著我們要將子數組劃分為兩個規模盡量相等的子數組。也就是,找到子數組的中央位置,比如mid,然后考慮求解兩個子數組A[low...mid]和A[mid+1...high]。A[low...high]的任何連續子數組A[i ...j]所處的位置必然是一下三種情況之一:
1.完全位于子數組A[low...mid]中,因此low<=i<=j<=mid
2.完全位于子數組A[mid+1...high]中,因此mid<i<=j<=high
3.跨越了中點,因此low<=i<=mid<j<=high
我們可以遞歸地求解A[low...mid]和A[mid+1...high]的最大子數組。剩下的全部工作就是尋找跨越中點的最大子數組,然后在三種情況中選取最大者。
時間復雜度為O(n)。
分治法python求解如下:
def max_cross_subarray(low, mid, high, array):max_low, max_high = low, highleft_sum = float("-inf")sum = 0for i in range(mid, low-1, -1):sum += array[i]if sum > left_sum:left_sum = summax_low = iright_sum = float("-inf")sum = 0for j in range(mid+1, high + 1):sum += array[j]if sum > right_sum:right_sum = summax_high = jmax_sum = left_sum + right_sumreturn(max_low, max_high, max_sum) def max_subarray(array, low, high):mid = (low + high)//2if low == high:return(low, high, array[low])else:#完全位于子數組A[low...mid]中(left_low, left_high, left_max) = max_subarray(array, low, mid)#完全位于子數組A[mid+1...high]中(right_low, right_high, right_max) = max_subarray(array, mid+1, high)#跨越了中點(mid_low, mid_high, mid_max) = max_cross_subarray(low, mid, high, array)#比較三種情況的最大值,求整體最大值if left_max > right_max and left_max > mid_max:max_sum = left_maxsub_low = left_lowsub_high = left_highelif right_max > left_max and right_max > mid_max:max_sum = right_maxsub_low = right_lowsub_high = left_highelse:max_sum = mid_maxsub_low = mid_lowsub_high = mid_highreturn(sub_low, sub_high, max_sum) #test if __name__ == '__main__':array = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7,]max = max_subarray(array, 0, len(array)-1)print(max) #output #(7,10,43)?
總結
以上是生活随笔為你收集整理的python求最大连续子数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果8p边缘都有缝隙么
- 下一篇: 第五人格:杰克怎么公主抱