【LeetCode每天一题】Maximum Subarray(最大子数组)
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
思路
这道题看到之后第一想到的就是使用动态规划来解决这个问题。使用动态规划需要申请一个辅助数组,另外还需要动态方程,方程为dp[i] = nums[i] + ( dp[i-1] if dp[i-1] > 0 else 0)。 这种解法的时间复杂度为O(n),空间复杂度为O(n)。
第二种思路就是我们设置一个sum_标志量和结果变量,然后从头遍历,使用sum_变量存储连续数组的和,如果当前小于0直接赋值为0。最后返回结果变量。时间复杂度为O(n),空间复杂度为O(1)。
第一种思路代码
1 class Solution(object):
2 def maxSubArray(self, nums):
3 """
4 :type nums: List[int]
5 :rtype: int
6 """
7 if len(nums) < 1 :
8 return 0
9 dp = [0] * len(nums) # 辅助数组
10 dp[0] = nums[0] # 记录nums第一个的值
11 max_num = dp[0] # 记录子数组最大的值
12 for i in range(1, len(nums)):
13 dp[i] = nums[i] + (dp[i-1] if dp[i-1]> 0 else 0) # 记录当前最大的子数组和的值
14 max_num = max(max_num, dp[i])
15 return max_num
第二种思路解决办法
1 class Solution(object):
2 def maxSubArray(self, nums):
3 """
4 :type nums: List[int]
5 :rtype: int
6 """
7 if len(nums) < 1 :
8 return 0
9 res, sum_ = nums[0], 0
10 for i in nums:
11 sum_ += i
12 res = max(sum_, res)
13 if sum_ < 0:
14 sum_ = 0
15 return res