53. Maximum Subarray
Easy
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max=nums[0];
for(int i=1;i<nums.size();i++){
nums[i]=nums[i-1]>0?nums[i]+nums[i-1]:nums[i];//在原数组上记录截至该元素最大的字段和,取决于之前的是否>=0
if(nums[i]>max) max=nums[i];
}
return max;
}
};
本文深入探讨了求解最大子数组和的经典算法,通过一个简单易懂的例子[-2,1,-3,4,-1,2,1,-5,4],详细讲解了如何找到连续子数组中和最大的解决方案。文章提供了O(n)复杂度的高效算法实现,并鼓励读者尝试使用分治策略寻找另一种解法。
342

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



