Leetcode 53. Maximum Subarray
2015-03-10 17:42
471 查看
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.
[Solution]
dynamic programming:
let local_suffix[0...i....n] represet max subarray contains the ith number in A[],
However, this uses O(n) memory. We can use just local_suffix instead.
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.
[Solution]
dynamic programming:
let local_suffix[0...i....n] represet max subarray contains the ith number in A[],
if (local_suffix[i - 1] <= 0) local_suffix[i] = A[i - 1]; else local_suffix[i] = local_suffix[i - 1] + A[i - 1];
int maxSubArray(int A[], int n) { if (n <= 0) return -1; int global_suffix = INT_MIN, *local_suffix = new int[n + 1]; local_suffix[0] = 0; for (int i = 1; i <= n; i++) { if (local_suffix[i - 1] <= 0) local_suffix[i] = A[i - 1]; else local_suffix[i] = local_suffix[i - 1] + A[i - 1]; if (global_suffix < local_suffix[i]) global_suffix = local_suffix[i]; } delete[] local_suffix; return global_suffix; }
However, this uses O(n) memory. We can use just local_suffix instead.
int maxSubArray(int A[], int n) { if (n <= 0) return -1; int global_suffix = INT_MIN, local_suffix; for (int i = 0; i < n; i++) { if (local_suffix <= 0) local_suffix = A[i]; else local_suffix = local_suffix + A[i]; if (global_suffix < local_suffix) global_suffix = local_suffix; } return global_suffix; }
相关文章推荐
- LeetCode -- 53. Maximum Subarray
- 【leetcode】53. Maximum Subarray
- [LeetCode]53. Maximum Subarray
- LeetCode53. Maximum Subarray
- 【LeetCode】 53. Maximum Subarray 最大子序列和
- [LeetCode]53. Maximum Subarray
- [Leetcode]53. Maximum Subarray
- LeetCode 53. Maximum Subarray
- leetcode53. Maximum Subarray
- leetcode-53. Maximum Subarray
- Leetcode 53. Maximum Subarray
- LeetCode 53. Maximum Subarray O(n)实现
- 【C++】【LeetCode】53. Maximum Subarray
- [leetcode] 53. Maximum Subarray
- LeetCode:53. Maximum Subarray
- leetcode 53. Maximum Subarray
- Leetcode题解 - 53. Maximum Subarray
- leetcode_53. Maximum Subarray-子数组最大和
- 【算法作业10】LeetCode 53. Maximum Subarray
- LeetCode 53. Maximum Subarray