连续子数组求和-LintCode
2017-10-10 09:18
369 查看
给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的下标。(如果两个相同的答案,请返回其中任意一个)
样例:
给定 [-3, 1, 3, -3, 4], 返回[1,4].
样例:
给定 [-3, 1, 3, -3, 4], 返回[1,4].
#ifndef C402_H #define C402_H #include<iostream> #include<vector> using namespace std; 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; if (A.empty()) return res; res.push_back(0); res.push_back(0); int len = A.size(); int sum = 0, max = INT_MIN; int start = 0, end = 0; for (int i = 0; i < len; ++i) { if (sum >= 0) { sum += A[i]; end = i; } else { sum = A[i]; start = end = i; } if (sum > max) { max = sum; res[0] = start; res[1] = end; } } return res; } }; #endif
相关文章推荐
- LintCode : 连续子数组求和
- 算法学习-连续子数组求和最大值
- 有一个数组,由正整数、负整数、零组成,求和最大的连续子数组
- 算法学习-连续子数组求和最大值
- 猿辅导2017校园招聘笔试题 求和为0的最长连续子数组
- lintcode-402-连续子数组求和
- lintcode循环数组之连续子数组求和
- “一个数组有正负0,求和为0的最长连续子数组”的失败解法
- 算法学习-连续子数组求和最大值
- lintcode,连续子数组求和
- LintCode: 连续子数组求和
- LintCode-合并排序数组 II
- LintCode求最大平均值子数组
- 动态规划--求最大连续子数组的和(Python实现)&求解最大连续乘积字串(Python实现)
- leetcode:Maximum Subarray(最大的连续子数组) 【面试算法】
- HDU2838 Cow Sorting 树状数组 区间求和加逆序数的应用
- poj1195Mobile phones【二维树状数组。单点更新/区间求和】
- 求连续子数组最大和问题的两种解法_PHP实现
- 【LintCode】数组的全排序(1)