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
.
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle
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
思路:
想不出来这种精妙的算法。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。