Leetcode: Maximum Subarray
来源:互联网 发布:淘宝店铺登录界面 编辑:程序博客网 时间:2024/06/07 08:24
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:
按理说,分治方法时间复杂度为O(nlgn),但测试用例时间花费反而小一些。可能跟测试集合有关系吧。
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) { int sum = 0; int largest = numeric_limits<int>::min(); for (int i = 0; i < n; ++i) { sum += A[i]; if (sum > largest) { largest = sum; } if (sum < 0) { sum = 0; } } return largest; }};分治方法:
class Solution {public: int maxSubArray(int A[], int n) { return maxSubArrayUtil(A, 0 , n - 1); } int maxSubArrayUtil(int A[], int low, int up) { if (low == up) { return A[low]; } else { int mid = (low + up) >> 1; int max_sum = max(maxSubArrayUtil(A, low, mid), maxSubArrayUtil(A, mid+1, up)); int sum = 0; int max_low = numeric_limits<int>::min(); for (int i = mid; i >= low; --i) { sum += A[i]; if (sum > max_low) { max_low = sum; } } sum = 0; int max_up = numeric_limits<int>::min(); for (int i = mid + 1; i <= up; ++i) { sum += A[i]; if (sum > max_up) { max_up = sum; } } return max(max_sum, max_low + max_up); } }};
按理说,分治方法时间复杂度为O(nlgn),但测试用例时间花费反而小一些。可能跟测试集合有关系吧。
0 0
- 【LeetCode】Maximum Subarray 和 Maximum Product Subarray
- LeetCode: Maximum Subarray
- LeetCode Maximum Subarray
- [Leetcode] Maximum Subarray
- LeetCode: Maximum Subarray
- leetcode 25: Maximum Subarray
- [LeetCode] Maximum Subarray
- [Leetcode] Maximum Subarray
- [LeetCode]Maximum Subarray
- [leetcode]Maximum Subarray
- LeetCode-Maximum Subarray
- [leetcode] Maximum Subarray
- LeetCode 45: Maximum Subarray
- LeetCode - Maximum Subarray
- LeetCode:Maximum Subarray
- LeetCode 53: Maximum Subarray
- 【leetcode】Maximum Subarray
- Leetcode Maximum Subarray
- 2013年终学习总结
- Linux下各种主要文件系统的读写性能测试 ------------实际系统中的Nand Flash速度测试结果
- 【DFS】POJ-3009 冰壶游戏
- 马达 vibrator的android的timed_output实现方式
- Xcode cannot run using the selected device. Choose a destination with a supported architecture
- Leetcode: Maximum Subarray
- linux,单用户模式下,修改ROOT密码时,键盘用没了。
- cppTest-3.0:指针相关-3(new&delete)
- iOS 5 ARC 入门
- iOS中Blocks的介绍
- Thinkpad SL400 功能键介绍
- 编程修养 from匠人的百宝箱
- 微分方程求解思考
- cppTest-3.0:指针相关-3(二维数组的n种new方式)