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.
class Solution {
public:
int maxSubArray(int A[], int n) {
if(n == 0) return 0;
if(n == 1) return A[0];
int max = A[0];
int currentsum = A[0];
for(int ii = 1; ii < n; ii ++) {
if(currentsum + A[ii] > 0) {
if(currentsum < 0)
currentsum = 0;
currentsum += A[ii];
if(currentsum > max) {
max = currentsum;
}
}
else
{
if(currentsum > A[ii]) {
if(currentsum > max) {
max = currentsum;
}
}
else {
if(A[ii] > max) {
max = A[ii];
}
}
currentsum = A[ii];
}
}
return max;
}
};
本文介绍了一种寻找具有最大和的连续子数组的算法实现。通过动态规划思想,该算法能够高效地找到给定数组中最大子数组的和。例如,在数组[-2,1,-3,4,-1,2,1,-5,4]中,连续子数组[4,-1,2,1]具有最大和6。
925

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



