[Leetcode 53, medium] Maximal subarray
2015-03-22 03:54
369 查看
Problem:
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.
Analysis:
Solutions:
C++:
Java:
Python:
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.
Analysis:
Solutions:
C++:
int maxSubArray(int A[], int n) { int max_sum = 0; int partial_sum = 0; for(int i = 0; i < n; ++i) { partial_sum += A[i]; if(i == 0 || partial_sum > max_sum) max_sum = partial_sum; if(partial_sum < 0) partial_sum = 0; } return max_sum; }
Java:
Python:
相关文章推荐
- LeetCode_OJ【53】Maximum Subarray
- Leetcode-53: Maximum Subarray
- 【LeetCode】325.Maximum Size Subarray Sum Equals k(Medium)解题报告
- [leetcode]53. Maximum Subarray 最大连续子串python实现【medium】
- LeetCode 53/152 Maximum Subarray/Maximum Product Subarray---DP **
- LeetCode:152_Maximum Product Subarray | 最大乘积连续子数组 | Medium
- Leetcode 53:Maximum Subarray
- [Leetcode 152, Medium] Maximum Product Subarray
- LeetCode:152_Maximum Product Subarray | 最大乘积连续子数组 | Medium
- LeetCode 53: Maximum Subarray
- LeetCode: -Dynamic Programming-Maximum Subarray[53]-子数组最大和
- [leetcode53]两种思路解决的Maximun Subarray
- LeetCode-Medium-Java-Subarray Sum Equals K
- LeetCode: 221_Maximal Square | 二维0-1矩阵中计算包含1的最大正方形的面积 | Medium
- LeetCode(53)Maximum Subarray
- LeetCode-53-Maximum Subarray(DP/分治)-Medium
- Leetcode 53-Maximum Subarray 解题报告
- 【LeetCode】560.Subarray Sum Equals K(Medium)解题报告
- [LeetCode-Algorithms-53] "Maximum Subarray" (2017.10.19-WEEK7)
- 【Leetcode】【Medium】Maximum Product Subarray