原题链接: https://leetcode.com/problems/maximum-subarray/
1. 题目描述
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.
寻找和最大的连续子数组
2. 解题思路
动态规划
我在这里只列出动态规划的思路,参考了 https://leetcode.com/problems/maximum-subarray/discuss/20193/DP-solution-and-some-thoughts 的做法。
最优化问题往往可以使用动态规划来解决。而动态规划法的精髓就在于记录前一个结果,利用前一个结果来推算后面的结果。
我使用int [] dp 数组来记录结果。dp[ i ] 中存储着 nums[ i ]之前的数以及nums[ i ]本身所能达到的最大的和。
最后的结果就是dp数组中的最大值了。
class Solution {
public int maxSubArray(int[] nums) {
int length = nums.length;
int[] dp = new int[length] ; //dp数组是存放最大和的数组
dp[0] = nums[0];//开始时,最大和就是第一个元素nums[0]
int res = dp[0];//开始时,最大和为dp[0]
for(int i =1;i<length;i++) {
dp[i] = nums[i]+ (dp[i-1]>0 ? dp[i-1] : 0);
//dp[i-1]是nums[i]之前的数能加到的最大的和,如果大于零,就要把它加上。
res = (dp[i] > res ? dp[i] : res);
//dp[i]如果比现有的结果要大,就更新结果
}
return res;
}
}