给定一个长度为 n 的数组 arr ,返回其中任意连续子数组的最大累加和
题目保证没有全为负数的数据
数据范围:,数组中元素值
要求:时间复杂度为,空间复杂度为
# # max sum of the subarray # @param arr int整型一维数组 the array # @return int整型 # class Solution: def maxsumofSubarray(self , arr ): # write code here s_max = max(arr[0], 0) sub_max = arr[0] for v in arr[1:]: sub_max += v if sub_max <= 0 : sub_max = 0 if s_max < sub_max: s_max = sub_max return s_max
class Solution: def maxsumofSubarray(self , arr ): sum=0 ans=0 length=len(arr) for i in range(len(arr)): sum+=arr[i] if sum>ans: ans=sum if sum<0: sum=0 return ans
class Solution: def maxsumofSubarray(self , arr ): # write code here tmp, res = 0, 0 for i in range(len(arr)): if arr[i] > 0: tmp += arr[i] else: tmp = max(0, res+arr[i]) if tmp > res: res = tmp return res
class Solution: def maxsumofSubarray(self , arr ): # write code here max_arr = [] max_sum = 0 for i in arr: if max_sum < 0: max_sum = i else: max_sum += i max_arr.append(max_sum) max_sum = max(max_arr) return max_sum设置一个累加和列表max_arr和一个最大值max_sum,每进行一步首先判断最大值max_sum是否小于0,如果小于0的话就将当前数组中的数i赋值给max_sum,每循环一次将当前最大值放入累加和列表中,全部循环完毕后求累加和列表Max_arr中的最大值
# # max sum of the subarray # @param arr int整型一维数组 the array # @return int整型 # class Solution: def maxsumofSubarray(self , arr ): #特殊情况 if(len(arr)<1): return 0 #普通情况 sumRes=arr[0] #初始状态 maxNum=sumRes #存储临时较大值 #转移状态方程 for i in range(1,len(arr)): if(sumRes>0): sumRes = sumRes + arr[i] else: sumRes = arr[i] maxNum=max(maxNum,sumRes) return maxNum
class Solution: def maxsumofSubarray(self , arr ): # write code here n = len(arr) if n==1: return arr[0] dp = [0]*n dp[0] = arr[0] for i in range(1,n): if dp[i-1]<0: dp[i] = arr[i] else: dp[i] = dp[i-1]+arr[i] return max(dp)
class Solution: def maxsumofSubarray(self , arr ): # write code here n = len(arr) if n==1: return arr[0] res, cur = arr[0], arr[0] for i in range(1,n): cur = max(cur+arr[i], arr[i]) res = max(res, cur) return res