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.
(数组连续子串的和最大)
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.
Example:
1. 动态规划
这个题目写出动规表达式就很容易得到具体的解法:dp[i+1] = max(dp[i]+nums[i+1], nums[i+1])。具体的解法如下:
1 | class Solution: |
2. 分治法
题中要求使用分治法来解决这个问题,我们可以分 3 类情况来讨论。对于一个数组 nums 的 [left, right]子串,其中点为 mid = (left + right) // 2,
- 答案序列完全在[left, mid - 1]中;
- 答案序列完全在[mid + 1, right]中;
- 答案序列为包含 mid 的左右延续的序列。
1 | class Solution: |