Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
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.
用DP的思想很快就得出O(n)解法。对于f(n)的最大值,判断f(n-1)与a[n]值的大小。如果f(n-1)
public int maxSubArray(int[] nums) {
int max = nums[0];
int result = max;
for(int i = 1;i < nums.length;i++){
max = (max > 0) ? (max + nums[i]) : nums[i];
if(max > result) result = max;
}
return result;
}
题目最后提到了分治法解决会很巧妙,于是在Discuss里看到某大神的分治法讲解。思路如下:
1、单独写一个计算函数,首先计算middle索引,递归调用本函数计算(left,middle-1)和(middle+1,right);
2、针对middle处的元素,一共有两种情况:最终的sum不包含它/包含它。
3、从middle开始,向left方向走,计算出此方向上的最大和;然后从middle向right方向走,计算出最大和;将二者加和就是包含middle值的最大和;
4、比较包含middle的最大和与1中计算出的middle左侧、右侧最大和,返回其中的最大值即可。
复杂度:T(n)=2T(n/2)+n, 为O(n*lgn)。不如 O(n)的快。