leetcode 53 最大子序和
class Solution:
def maxSubArray(self, nums) -> int:
if not nums:
return None
lmax, larr = -9e32, len(nums)
for i in range(1, larr + 1):
j = 0
while i + j <= larr:
tmp = sum(nums[j: i + j])
lmax = tmp if tmp > lmax else lmax
j += 1
return lmax
class Solution:
def maxSubArray(self, nums) -> int:
if not nums:
return None
pre, cur, res = -1e32, None, -1e32
for i, val in enumerate(nums):
cur = val if val > pre + val else pre + val
pre, res = cur, res if res > cur else cur
return res
class Solution:
def maxSubArray(self, nums) -> int:
if not nums:
return None
pre_max = ret = nums[0]
nums = nums[1:]
for i in nums:
pre_max = i if i > i + pre_max else i + pre_max
ret = ret if ret > pre_max else pre_max
return ret
class Solution:
def maxSubArray(self, nums) -> int:
if not nums:
return None
def get_max(nums, st, end):
pre_max = ret = nums[0]
for i in range(st, end):
pre_max = nums[i] if nums[i] > nums[i] + pre_max else nums[i] + pre_max
ret = ret if ret > pre_max else pre_max
return ret
return get_max(nums, 1, nums.__len__())
def maxSubArray(nums, start, end):
if not nums:
return None
if start == end:
return nums[start]
mid = (start + end) // 2
left = maxSubArray(nums, start, mid)
right = maxSubArray(nums, mid + 1, end)
pre, post = nums[mid], nums[mid + 1]
max_pre_post = pre
for i in range(mid - 1, start - 1, -1):
pre += nums[i]
max_pre_post = max_pre_post if max_pre_post > pre else pre
pre, max_pre_post = max_pre_post, post
for i in range(mid + 2, end + 1):
post += nums[i]
max_pre_post = max_pre_post if max_pre_post > post else post
post = max_pre_post
return max(left, right, pre + post)