【LeetCode】Maximum Subarray (最大连续子序列和)
2013-10-03 09:17
316 查看
描述:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
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
代码:O(n)
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
代码:O(n)
class Solution { public: int maxSubArray(int A[], int n) { // Note: The Solution object is instantiated only once and is reused by each test case. int maxendinghere = 0,maxsofar = 0; for(int i = 0; i<n; i++) { maxendinghere = max(maxendinghere + A[i],0); maxsofar = max(maxsofar,maxendinghere); } if(maxsofar == 0) //数组元素全部非正数 { int tmp = A[0]; for(int i = 1; i<n; i++) { tmp = max(tmp,A[i]); } return tmp; } return maxsofar; } };
相关文章推荐
- LeetCode:Maximum Subarray(最大连续子序列和DP)
- 【LeetCode】53.Maximum Subarray最大连续子序列和
- 【leetcode】53. Maximum Subarray 连续子序列的最大和
- leetcode | Maximum Subarray 最大连续子序列的和
- LeetCode--Maximum Subarray 最大连续子序列和 (动态规划)
- 最大连续子序列的和与积
- (java)整数数组中求最大连续子序列之和,并且记录开始和结束位置
- 最大连续子序列和
- HDU 1231 最大连续子序列
- 【练习09】简单动态规划 1001 最大连续子序列
- 连续子序列最大和问题的四种经典解答
- 求连续最大子序列积 - leetcode. 152 Maximum Product Subarray
- Codeforces Round #407(Div. 2)C. Functions again【思维+最大连续子序列的和】
- leetcode 674. Longest Continuous Increasing Subsequence 最长递增连续子序列
- [leetcode]Maximum Product Subarray最大子序列乘积
- hdoj 1231 最大连续子序列
- hdu 1231 最大连续子序列
- 九度1011:最大连续子序列
- 最大连续子序列和
- 最大连续子序列的和