描述
iven an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
解析
根据题意,设置两个变量 l 和 g,l 表示以当前位置结尾的子串的最大值, g 表示的是全局最大值,这个值肯定是来自于若干个 l 值。时间复杂度为 O(N),空间复杂度为 O(1)。
解答
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = g = float("-inf")
for i in nums:
l = max(l+i,i)
# print(l)
g = max(g,l)
return g
运行结果
Runtime: 44 ms, faster than 96.59% of Python online submissions for Maximum Subarray.
Memory Usage: 12.2 MB, less than 78.58% of Python online submissions for Maximum Subarray.
每日格言:成功的诀窍在于永不改动既定的方针。
请作者吃一支雪糕 支付宝