码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 【 Maximum Subarray 】python 实现

时间:2015-01-22 01:43:10      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

题目

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.

click to show more practice.

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

 

思路

想不出来这种精妙的算法。

leetcode 【 Maximum Subarray 】python 实现

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4240510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!