给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。(一个也不会,难受)
class Solution(object):
def maxSubArray1(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.max_sub(0, len(nums) - 1, nums)[-1]
def max_sub(self, start, end, nums):
if start == end:
return nums[start], nums[start], nums[start], nums[start]
mid = (start + end) >> 1
left_left_sum, left_right_sum, left_all_sum, left_mid_sum = self.max_sub(start, mid, nums)
right_left_sum, right_right_sum, right_all_sum, right_mid_sum = self.max_sub(mid + 1, end, nums)
return max(left_left_sum, left_all_sum + right_left_sum),
max(right_right_sum, right_all_sum + left_right_sum),
left_all_sum + right_all_sum,
max(left_right_sum + right_left_sum, max(left_mid_sum, right_mid_sum))
def maxSubArray2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# pre, max_ans = 0, nums[0]
pre = 0
max_ans = nums[0]
for item in nums:
# pre记录是当前值和前n个连续值的最大值;当前n个连续值,小于当前值时直接将pre指向当前值
# 也就是前n个连续数不存在最大连续数组,直接抛弃前n项,从n+1项继续记录
pre = max(pre + item, item)
# max_ans一直记录的是连续子项的最大值
max_ans = max(max_ans, pre)
return max_ans
def maxSubArray3(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.get_info(nums, 0, len(nums) - 1).m_sum
def get_info(self, nums, left, right):
if left == right:
return Status(nums[left], nums[left], nums[left], nums[left])
mid = (left + right) >> 1
l_sub = self.get_info(nums, left, mid)
r_sub = self.get_info(nums, mid+1, right)
return self.push_up(l_sub, r_sub)
def push_up(self, l, r):
i_sum = l.i_sum + r.i_sum
l_sum = max(l.l_sum, l.i_sum + r.l_sum)
r_sum = max(r.r_sum, r.i_sum + l.r_sum)
m_sum = max(max(l.m_sum, r.m_sum), l.r_sum + r.l_sum)
return Status(l_sum, r_sum, m_sum, i_sum)
def maxSubArray4(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
tmp_list = []
max_sum = nums[0]
while nums:
tmp_list.append(nums.pop(0))
if sum(tmp_list) > max_sum:
max_sum = sum(tmp_list)
if sum(tmp_list) < 0:
tmp_list = []
return max_sum
def maxSubArray5(self, nums):
"""最原始的dp方式
:type nums: List[int]
:rtype: int
"""
length = len(nums)
dp = [0 for _ in range(length)]
dp[0] = nums[0]
max_value = dp[0]
for i in range(length):
dp[i] = max(dp[i-1] + nums[i], nums[i])
max_value = max(max_value, dp[i])
return max_value
def maxSubArray(self, nums):
"""暴力递归,算出每个未知的最大值
:type nums: List[int]
:rtype: int
"""
max_value = float("-inf")
length = len(nums)
for i in range(length):
sum_ = 0
for j in range(i, length):
sum_ += nums[j]
max_value = max(max_value, sum_)
return max_value
class Status:
def __init__(self, l_sum, r_sum, m_sum, i_sum):
self.l_sum = l_sum
self.r_sum = r_sum
self.m_sum = m_sum
self.i_sum = i_sum
if __name__ == '__main__':
s1 = Solution()
s = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(s1.maxSubArray1(s))