题目描述
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
题解
暴力解法
两层for循环嵌套解题
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum = nums[0]
for i in range(len(nums)):
sum_i = nums[i]
sum_i_max = sum_i
for j in range(i+1,len(nums)):
sum_i += nums[j]
sum_i_max = max(sum_i_max, sum_i)
max_sum = max(max_sum, sum_i_max)
return max_sum
动态规划解法
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum = nums[0]
pre = 0
for num in nums:
pre = max(pre+num, num)
max_sum = max(pre, max_sum)
return max_sum
貌似动态规划的解法还挺慢的,不知道是服务器现在负载很大的原因导致很慢,还是算法很慢的原因。
相关题目
最长子序列