44最小子数组
题目
给定一个整数数组,找到一个具有最小和的子数组。返回其最小和。
注意事项
子数组最少包含一个数字
样例
给出数组[1, -1, -2, 1],返回 -3
思路
这道题是要在原来的整数数组中按数组顺序找到满最小和的数组。例如[1, -2,1,-1, -2, 1]–>[-2,1,-1, -2]=-4
代码
class Solution:
"""
@param nums: a list of integers
@return: A integer denote the sum of minimum subarray
"""
def minSubArray(self, nums):
# write your code here
x1=nums[0]
x2=nums[0]
for i in nums[1:]:
x1=min(i,x1+i)
x2=min(x1,x2)
return x2
41最大子数组
题目
给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。
注意事项
子数组最少包含一个数
样例
给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6
代码
class Solution:
"""
@param nums: A list of integers
@return: An integer denote the sum of maximum subarray
"""
def maxSubArray(self, nums):
# write your code here
x1=nums[0]
x2=nums[0]
for i in nums[1:]:
x1=max(i,i+x1)
x2=max(x1,x2)
return x2