求数组的子数组之和的最大值
《编程之美》的2.14中抛出了这么一道题。我的解法如下:
#!/usr/bin/env python def getMaxSubset(data): if len(data)==0: return curSum = maxSum = data[0] i = 1 while i < len(data): if curSum<=0: curSum = data[i] else: curSum+=data[i] if curSum>=maxSum: maxSum = curSum i+=1 return maxSum a1 = [-2, 5, 3, -6, 4, -8, 6] a2 = [-2, 3, -4] a3 = [1, -2, 3, 5, -3, 2] a4 = [0, -2, 3, 5, -1, 2] a5 = [-9, -8, -6, -5, -2] a6 = [0, 0, 0, 0] a7 = [-2,-3, 4,5,-2,6] print getMaxSubset(a1) print getMaxSubset(a2) print getMaxSubset(a3) print getMaxSubset(a4) print getMaxSubset(a5) print getMaxSubset(a6) print getMaxSubset(a7)
输出为:
8
3
8
9
-2
0
13
这样只需要扫描一遍数组,时间复杂度为O(N).