LeetCode-连续子数组的最大和
2017-03-10 14:41
387 查看
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.
click to show more practice.
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.
int maxSubArray(int A[], int n) {
int curSum = 0;
int maxSum = A[0];
for(int j = 0; j < n; j++) {
if(curSum >= 0) {
curSum += A[j];
}
else {
curSum = A[j];
}
if(curSum > maxSum) {
maxSum = curSum;
}
}
return maxSum;
}
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.
click to show more practice.
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.
int maxSubArray(int A[], int n) {
int curSum = 0;
int maxSum = A[0];
for(int j = 0; j < n; j++) {
if(curSum >= 0) {
curSum += A[j];
}
else {
curSum = A[j];
}
if(curSum > maxSum) {
maxSum = curSum;
}
}
return maxSum;
}
相关文章推荐
- LeetCode:152_Maximum Product Subarray | 最大乘积连续子数组 | Medium
- LeetCode 152. Maximum Product Subarray--连续子数组最大乘积
- leetcode-53 Maximum Subarray 连续子数组的最大和
- 每天一道LeetCode-----找到给定数组的连续子数组,使这个子数组的和最大,要求复杂度为O(n)
- 面试题31:连续子数组的最大和(Leetcode-53:Maximum Subarray)
- 每天一道LeetCode----从数组中选择若干不连续元素使得总和最大
- 【leetcode笔记】如何求数组中连续和的最大值----Maximum Subarray问题
- LeetCode | Maximum Subarray(连续最大子数组)
- LeetCode:152_Maximum Product Subarray | 最大乘积连续子数组 | Medium
- Maximum Subarray 最大子数组和(连续)@LeetCode
- 动态规划算法 (微软笔试题,求连续子数组的最大和)
- 求一个数字数组里的最大连续数字的个数
- 求数组中连续子数组的最大和
- 数组非连续元素最大和
- 求随机数组中连续数三个最大的
- 连续子数组的最大和
- 求数组中连续子序列的最大和
- 面试题31:连续子数组的最大和
- 利用动态规划求连续数组最大和以及最大子矩阵的和
- 程序员编程艺术:第七章、求连续子数组的最大和