对于非环形数组,求解和值最大子段的方法见之前一遍文章;
对于环形数组,需要考虑最大和值子段越过首尾边界的情况,解决方法比较简单,即将数组处理两遍; 需要注意子段长度不可以超过整个数组长度;
1 #! -*- coding: utf-8 -*- 2 3 loop = (4, -3, 2, -4, 1, 5, -3, -4, 3) 4 #loop = (4, 3, 2, 4, 1, 5, 3, 4, 3) 5 #loop = (-4, -3, -2, -4, -1, -5, -3, -4, -3) 6 7 # 求解和值最大子段 8 # 算法关键是将和值对整体不利的子序列舍弃,修减问题树 9 # 复杂度O(n) 10 # 为处理循环数组,遍历数组两遍,注意子段长度是否达到了数组长度 11 def big_sub(): 12 try_sum = 0 13 try_start = 0 14 length = 0 # 15 try_length = 0 # 16 17 start = 0 18 end = 0 19 sum = 0 20 big = loop[0] 21 big_index = 0 22 23 for index in range(0, 2*len(loop)): # 24 i = index % len(loop) # 25 26 if try_sum >= 0: 27 try_sum += loop[i] 28 try_length += 1 # 29 if (try_sum > sum): 30 sum = try_sum 31 length = try_length # 32 if length >= len(loop): # 33 break # 34 end = i 35 start = try_start 36 else: # try_sum < 0 37 try_sum = loop[i] 38 try_start = i 39 try_length = 1 # 40 41 if loop[i] > big: 42 big = loop[i] 43 big_index = i 44 45 if sum == 0: 46 sum = big 47 start = end = big_index 48 49 if start <= end and length < len(loop): # 50 print loop[start:end+1], 51 elif length >= len(loop): 52 print loop, 53 else: # 54 print loop[start:], 55 print loop[:end+1], 56 print sum 57 58 59 big_sub()
注:红字部分是为处理环形数组而修改的代码