Maximum Subarray 题解
题目来源:Maximum Subarray
> 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.
解题思路:
注意此例是连续subarray,且最少得选1个。
若当前i,前面i-1的结果若为负的话,新序列就从当前A[i]开始算起了,不然就将当前A[i]附加上去。
DP, O(n) 空间
int maxSubArray(int A[], int n)
{
assert(n != 0);
vector<int> dp(n, 0);
dp[0] = A[0];
int result = A[0];
for(int i = 1; i < n; i++)
{
if(dp[i-1] < 0)
dp[i] = A[i];
else
dp[i] = dp[i-1] + A[i];
result = std::max(result, dp[i]);
}
return result;
}DP, O(1) 空间
上面的优化一下即可。
分治, O(nlogn)
分治算法:要么左半/右半,要么包括中间的和左右两边都有部分, 时间复杂度O(NlogN).
参考资料:
Last updated
Was this helpful?