描述
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){
int result = INT_MIN, f = 0;
for(int i = 0;i < n ; i++){
f = max(f + A[i], A[i]); //连续和 ? 当前值
result = max(result, f); //更新结果
}
return result;
}
};

参考资料:
LeetCode图解
本文探讨了在至少包含一个数的数组中寻找具有最大和的连续子数组的问题。通过示例[-2,1,-3,4,-1,2,1,-5,4],解释了如何找到最大和为6的子数组[4,-1,2,1]。文章提供了C++代码实现,采用动态规划思想,逐元素迭代更新最大子数组和。
552

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



