题意:找出一个数组中某一段累加和最大
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
一看到题目,这不就是算法导论的股票问题么...好吧,按着分治策略写,写着写着发现还是有点麻烦啊。。。虽然思想不难,这就是个easy题为啥这么难。。。然后就没考虑用分治,反正也就O(n),一次循环找最大也可以啊,代码如下:
class Solution {
public int maxSubArray(int[] nums) {
int result = nums[0], sum = nums[0];
for (int i = 1; i < nums.length; i++){
sum = Math.max(sum + nums[i], nums[i]);//决定是当前位置(nums[i])还是累加值(sum + nums[i]),即不停的寻找最大的新值,方法是如果前面的累加还不如新出现的值大,那肯定选择新出现的值;如果累加的大那就继续累加。
result = Math.max(result, sum);//决定目前的最大值(sum)还是之前的最大值(result),即我累加但不一定有以前的好,因为有可能加了一个负的数,那要有一个保存之前最大值的数。
}
return result;
}
}
好的,然后偷偷瞄了下discussion的分治答案,果然写的很好- -
class Solution {
public int maxSubArray(int A[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(n==0) return 0;
return maxSubArrayHelperFunction(A,0,n-1);
}
private int maxSubArrayHelperFunction(int A[], int left, int right) {
if(right == left) return A[left];
int middle = (left+right)/2;
int leftans = maxSubArrayHelperFunction(A, left, middle);
int rightans = maxSubArrayHelperFunction(A, middle+1, right);
int leftmax = A[middle];
int rightmax = A[middle+1];
int temp = 0;
for(int i=middle;i>=left;i--) {
temp += A[i];
if(temp > leftmax) leftmax = temp;
}
temp = 0;
for(int i=middle+1;i<=right;i++) {
temp += A[i];
if(temp > rightmax) rightmax = temp;
}
return max(max(leftans, rightans),leftmax+rightmax);
}
}