class Solution {
//OJ suggest to solve this problem using D&C, but its time complexity is O(nlogn), right?
//So I choose the O(n) version to implement
public:
int maxSubArray(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(0 == n) return 0;
int ans = A[0];
int local = 0;
for (int i = 0; i < n; ++i)
{
local = local > 0 ? local+A[i] : A[i];
ans = max(local, ans);
}
return ans;
}
};
second time
class Solution {
public:
int maxSubArray(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n == 0) return 0;
int curSum = A[0];
int maxSum = curSum;
for(int i = 1; i < n; ++i)
{
if(curSum+A[i] > A[i]) curSum = curSum+A[i];
else curSum = A[i];
maxSum = max(maxSum, curSum);
}
return maxSum;
}
};
本文介绍了一种求解一维数组中最大子数组和的线性时间复杂度算法实现。通过遍历数组并使用局部变量跟踪当前子数组之和,该方法能够在O(n)的时间复杂度内找到具有最大和的连续子数组。
1650

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



