leetcode 【 Maximum Subarray 】python 实现
题目:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4]
,
the contiguous subarray [4,−1,2,1]
has the largest sum = 6
.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle
代码:oj测试通过 Runtime: 80 ms
1 class Solution: 2 # @param A, a list of integers 3 # @return an integer 4 def maxSubArray(self, A): 5 curr_sum = 0 6 max_sum = -100000 7 for i in range(len(A)): 8 if curr_sum < 0 : 9 curr_sum = 0 10 curr_sum = curr_sum + A[i] 11 max_sum = max(curr_sum, max_sum) 12 return max_sum
思路:
想不出来这种精妙的算法。
隔了一天Google到了一篇解释日志:
http://blog.csdn.net/linhuanmars/article/details/21314059
这个把这道题的背后思想解释的很好,有些受益。