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
.
1、该题求连续子串最大和。
2、用Max[i]表示以i结尾的连续子串最大和,因此Max[i]只与Max[i - 1]有关。
3、当Max[i - 1] > 0时,Max[i] = Max[i - 1] + nums[i],当Max[i - 1] <= 0时,Max[i] = nums[i]。
Java代码如下所示:
public class Solution {
public int maxSubArray(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int[] Max = new int[nums.length];
int result;
Max[0] = result = nums[0];
for(int i = 1; i < nums.length; i++) {
if(Max[i - 1] > 0) {
Max[i] = Max[i - 1] + nums[i];
} else {
Max[i] = nums[i];
}
if(result < Max[i]) {
result = Max[i];
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {-2,1,-3,4,-1,2,1,-5,4};
Solution solution = new Solution();
System.out.println(solution.maxSubArray(nums));
}
}