题目
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
.
我的解法
如果采用暴力方法,不难。但是还是花了我很长时间才调试通过。当然时间复杂度比较高,为 O(n2) 。在中间调试的过程中,还出现过几次 TimeLimitExceeded !
我的代码:
public class Solution {
public int maxSubArray(int[] nums) {
int len = nums.length;
int max = nums[0];
for (int i = 0; i < len; i++) {
int sum = 0;
for (int j = i; j < len; j++) {
sum += nums[j];
if (sum > max) {
max = sum;
}
if (sum < 0)
break;
}
}
return max;
}
}
优化后的代码:
采用动态规划的思想:[参考leetcode讨论区高票答案]
1.从nums[1]
开始扫描,并在扫描过程中保存目前为止最大子串的和——MaxSoFar
,其中MaxSoFar
初始化为nums[0]
;
2.假设我们已经找了nums[1..i-1]
中的最大子数组的和,接下需要思考如何能得到nums[1..i]
中的最大子数组的和;
3.MaxSoFar = max{ MaxSoFar,MaxEndHere }
,其中MaxEndHere
为以nums[i]
结尾的子串和的最大值
4.当前的MaxEndHere = max{ 之前的MaxEndHere+nums[i], nums[i]}
public class Solution {
public int maxSubArray(int[] nums) {
int MaxSoFar = nums[0];
int MaxEndHere = nums[0];
for (int i = 1; i < nums.length; i++) {
MaxEndHere = Math.max(nums[i] + MaxEndHere, nums[i]);
MaxSoFar = Math.max(MaxEndHere, MaxSoFar);
}
return MaxSoFar;
}
}