Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
[−2,1,−3,4,−1,2,1,−5,4]
,the contiguous subarray
[4,−1,2,1]
has the largest sum = 6
.
More practice:
比较简单的DP题目,我们全程保持最优解以及以当前元素结尾的连续子数组的最大和。
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
public int maxSubArray(int[] A) { int n = A.length; int max = A[0], result = A[0]; for(int i = 1; i < n; i++) { max = Math.max(A[i] + max, A[i]); result = Math.max(max, result); } return result; }这道题还有一种变种,这里是只寻找一个连续的子数组,变种是让你寻找m个连续的子数组,求解使得其和最大,这个问题的解法我稍后再补上。
没有评论:
发表评论