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 | Input: [-2,1,-3,4,-1,2,1,-5,4], |
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
,dp[i]
表示nums[0:i]
的最大和,状态转移方程:dp[i]=max(dp[i-1] + nums[i], nums[i])
代码:
1 | class Solution: |
我们可以维护一个变量tmp_ans
以节省空间,在遍历过程中判断tmp_ans
是否小于零,若小于零,则重置tmp_ans
为0,即改变求和起点,重新求和。
1 | import sys |