LeetCode 53. Maximum Subarray
53. Maximum Subarray
Difficulty: Medium
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.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
典型的 DP ,解题时间复杂度 O(n)
递推方程
curr(i) = max{curr(i-1), 0} + arr[i]
if curr(i) > ret
then ret = curr(i)
解题代码
int maxSubArray(int* nums, int numsSize) {
int curr = 0;
int ret = nums[0];
for (int i = 0; i < numsSize; i++) {
if (curr > 0) {
curr += nums[i];
} else {
curr = nums[i];
}
if (curr > ret) {
ret = curr;
}
}
return ret;
}
cost : 4ms
智慧在街市上呼喊,在宽阔处发声。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步