#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
53:maximum Subarray
https://leetcode.com/problems/maximum-subarray/
Find the contiguous subarray within an array (containing at least one number) which have 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 had figured out the O (n) solution, try coding another solution using the divide and conquer approach,
Which is more subtle.
= = = Comments by dabay===
One-dimensional dynamic planning.
The basic idea of dichotomy is: separating from the middle, recursion on both sides, and dealing with the cross-boundary situation.
Http://www.cnblogs.com/springfor/p/3877058.html
‘‘‘
Class Solution:
# @param A, a list of integers
# @return An integer
def maxsubarray (self, A):
If Len (A) = = 0:
return 0
Max_so_far = Max_ending_here = A[0]
For I in xrange (1, Len (A)):
Max_ending_here = max (Max_ending_here + a[i], A[i])
Max_so_far = Max (Max_so_far, Max_ending_here)
Return Max_so_far
def main ():
Sol = solution ()
Nums = [-2, 1,-3, 4,-1, 2, 1,-5, 4]
Print Sol.maxsubarray (nums)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]53:maximum Subarray