Daily LeetCode 53. Maximum Subarray

https://leetcode.com/problems/maximum-subarray/

Medium

问题描述

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

1
2
3
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.

思路及代码:

给定一个数组,求和最大的子串。

动态规划:

虽然这一题也是要求子串的问题,但是跟昨天的不同,我们不需要维护二维数组,因为这条题目的最终目的是求和。

我们只需要一个一维数组dpdp[i]表示nums[0:i]的最大和,状态转移方程:dp[i]=max(dp[i-1] + nums[i], nums[i])

代码:

1
2
3
4
5
6
7
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = [0] * len(nums)
for i in range(len(nums)):
dp[i] = max(dp[i-1] + nums[i], nums[i])

return max(dp)

我们可以维护一个变量tmp_ans以节省空间,在遍历过程中判断tmp_ans是否小于零,若小于零,则重置tmp_ans为0,即改变求和起点,重新求和。

1
2
3
4
5
6
7
8
9
10
11
import sys
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum = -sys.maxsize - 1
tmp_ans = 0
for i in range(len(nums)):
if tmp_ans < 0: tmp_ans = 0
tmp_ans += nums[i]
max_sum = max(tmp_ans, max_sum)

return max_sum