leetcode_question_53 Maximum Subarray
2013-09-15 16:41
295 查看
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
the largest sum =
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:
Divide and Conquer:
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:
int maxSubArray(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int max = A[0]; int currentsum = A[0]; for(int i = 1; i < n; ++i){ if(currentsum < 0) currentsum = 0; currentsum += A[i]; if(currentsum > max) max = currentsum; } return max; }
Divide and Conquer:
int calmaxsubarr(int A[], int begin, int end){ if(begin == end) return A[begin]; int mid = (end-begin)/2 + begin; int left = calmaxsubarr(A, begin, mid); int right = calmaxsubarr(A, mid+1, end); int lefthalf = A[mid]; int tmp = A[mid]; for(int i = mid -1; i >= begin; i--){ tmp += A[i]; if(tmp > lefthalf) lefthalf = tmp; } int righthalf = A[mid+1]; tmp = A[mid+1]; for(int i = mid +2; i <= end; ++i){ tmp += A[i]; if(tmp > righthalf)righthalf = tmp; } int middle = lefthalf + righthalf; int res = left > right ? left : right; res = res > middle ? res : middle; return res; } int maxSubArray(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function return calmaxsubarr(A, 0, n-1); }
相关文章推荐
- (leetcode) 238. Product of Array Except Self My Submissions QuestionEditorial Solution
- LeetCode(53) Maximum Subarray
- [leetcode53]两种思路解决的Maximun Subarray
- leetcode-53 Maximum Subarray
- leetcode_question_67 Add Binary
- leetcode_question_97 Interleaving String
- leetcode_question_113 Path Sum II
- leetcode_question_107 Binary Tree Level Order Traversal II
- leetcodequestion_56 Merge Intervals
- LeetCode Question Difficulty Distribution : Sheet1
- leetcode.(53).205. Isomorphic Strings
- LeetCode 53~54
- leetcode question 95: Unique Binary Search Trees II
- Leetcode 53. 最大子序和
- leetcode_53题——Maximum Subarray(动态规划)
- 【LEETCODE】53-Maximum Subarray
- LeetCode -- Product of Array Except Self My Submissions Question
- LeetCode 53: Maximum Subarray
- LeetCode-53-Maximum Subarray(C语言实现)
- LeetCode 53/152 Maximum Subarray/Maximum Product Subarray(动态规划)