题目链接:maximum-subarray
/**
*
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.
*
*/
public class MaximumSubarray {
//解法一
public int maxSubArray(int[] A) {
int max = Integer.MIN_VALUE;
int sum = 0;
for (int i = 0; i < A.length; i++) {
sum += A[i];
if(sum > max) max = sum;
if(sum < 0) sum = 0;
}
return max;
}
//解法二
// 201 / 201 test cases passed.
// Status: Accepted
// Runtime: 238 ms
// Submitted: 0 minutes ago
//保存版起始点和结束点
static int maxSubArray1(int[] A) {
int max = Integer.MIN_VALUE;
int beginIndex, endIndex;
int sum = 0;
int tempIndex = 0;
for (int i = 0; i < A.length; i++) {
sum += A[i];
if(sum > max) {
beginIndex = tempIndex;
endIndex = i;
max = sum;
}
if(sum < 0) {
tempIndex = i;
sum = 0;
}
}
return max;
}
public static void main(String[] args) {
System.out.println(maxSubArray1(new int[]{ -2, 1, -3, 4, -1, 2, 1, -5, 4}));
System.out.println(maxSubArray1(new int[]{ 1, 1, 1, 4, 1, -2, -1, -5, 4}));
}
}

本文介绍了两种解决最大连续子数组和问题的方法,包括一种优化的解决方案,通过迭代计算子数组和并更新最大值。

1148

被折叠的 条评论
为什么被折叠?



