[leetcode]53. Maximum Subarray 最大连续子串python实现【medium】

来源:互联网 发布:苹果6打不开数据流量 编辑:程序博客网 时间:2024/06/04 18:23

http://blog.csdn.net/zl87758539/article/details/51676108


题目:

Maximum Subarray
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.

题目是说,给你一串数,有正有负 要求出最大的连续子串。

其实就是标准的动态规划问题:
随着遍历这个数组,在到每一个位置的时候,弄一个局部最大L值,代表以当前位置为结尾的最大子串,比如说我遍历到第i个,那么以第i个为结尾的最大子串就是我们要求的L。

比如这个题目:
-2 , 1, −3,4,−1,2,1,−5,4
位置0,L=x=-2,没得选
位置1,要以x=1为结尾的最大的,那肯定不要带上之前的-2,只要1就好L=x=1
位置2,因为本身x=-3,加上上一个位置L 是正数1,所以L=L+x=-3+1=-2。
下面以此类推得到:

对应的L应该是:
-2, 1, -2,4,3,5,6,-1,3

而全局最大值G就是我们最终想要的结果,
肯定这个全局最大值出自局部最大值。
(因为全局最大的那个子串的结尾肯定在数组里,言外之意就是不管怎么样这个G都肯定出自L)
最后找到最大的那个L就是我们想要的G了。

class Solution(object):    def maxSubArray(self, nums):        l = g = -1000000000        for n in nums:            l = max(n,l+n)            g = max(l,g)        return g
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10


阅读全文
0 0
原创粉丝点击