LeetCode 53: Maximum Subarray
2015-10-30 13:49
393 查看
Maximum Subarray
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.
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.
解题思路
class Solution { public: int maxSubArray(vector<int>& nums) { int maxSubSum = INT_MIN; int preSubSum = 0; for (int i = 0; i < nums.size(); ++i) { preSubSum = (preSubSum < 0) ? nums[i] : preSubSum + nums[i]; maxSubSum = max(maxSubSum, preSubSum); } return maxSubSum; } };
相关文章推荐
- 基于Android中dp和px之间进行转换的实现代码
- Android中dip、dp、sp、pt和px的区别详解
- LFC1.0.0 版本发布
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Android px、dp、sp之间相互转换
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- android中像素单位dp、px、pt、sp的比较