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 Solution {
// dp[i] = max(A[i], dp[i - 1] + A[i])
public int maxSubArray(int[] A) {
if (A == null || A.length == 0)
return 0;
int[] dp = new int[A.length];
dp[0] = A[0];
int max = dp[0];
for (int i = 1; i < A.length; i++) {
dp[i] = Math.max(A[i], A[i] + dp[i - 1]);
if (dp[i] > max)
max = dp[i];
}
return max;
}
}
本文介绍了一个算法来找到数组中具有最大和的连续子数组,通过动态规划实现,详细解释了算法原理和步骤。
209

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



