题目:
https://leetcode-cn.com/problems/maximum-subarray/
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
s = float("-inf")
temps = 0
for i in range(len(nums)):
if temps+nums[i] < 0:
temps = 0
elif temps+nums[i] >= 0:
temps += nums[i]
s = max(s,temps)
if s == float("-inf"):
return max(nums)
return s
思路:其实就是用变量s记录最大和,临时变量temps记录连续和,如果连续和小于0,则应该不和后面相加,所以置为0,否则继续和后面相加,并和当前最大值s比较。