[LintCode] Continuous Subarray Sum
2015-11-09 10:17
387 查看
Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number. (If their are duplicate answer, return anyone)
For this problem, we first need to track subarray’s start point, and the maxSum. O(n) time complexity.
For this problem, we first need to track subarray’s start point, and the maxSum. O(n) time complexity.
class Solution { public: /** * @param A an integer array * @return A list of integers includes the index of * the first number and the index of the last number */ vector<int> continuousSubarraySum(vector<int>& A) { // Write your code here vector<int> res(2,-1); if(A.empty()) return res; int maxSum = INT_MIN, sum = 0, start = 0, end = 0; for(int i = 0; i<A.size(); ++i){ sum += A[i]; if(sum > maxSum){ maxSum = sum; res[0] = start; res[1] = i; } if(sum<0) { start = i+1; sum = 0; } } return res; } };
相关文章推荐
- LintCode-最大数
- Subtree
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- 中位数 21% 通过 给定一个未排序的整数数组,找到其中位数。 中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数
- LintCode 翻转二叉树
- LintCode 寻找缺失的数
- Lintcode 二叉树的后序遍历
- Lintcode 二叉树中序遍历
- Lintcode 二叉树前序遍历
- Lintcode 尾部零的个数
- Lintcode 比较字符串
- Lintcode 主元素
- Lintcode解题笔记 - 岛屿的个数
- LintCode -合并两个排序链表
- 20150708 lintcode 总结 Binary Tree Maximum Path Sum Show result *****
- 20150708 lintcode 总结 Minimum Path Sum