lintcode,连续子数组求和
2016-12-18 16:31
169 查看
给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的下标。(如果两个相同的答案,请返回其中任意一个)
样例
给定 [-3, 1, 3, -3, 4], 返回[1,4].
解题思路:类似最大子数组的思路,需要注意的是索引合适改变,start在sum改变时改变,end一直改变,但是只在max发生改变时纪录下start和end。
一刷ac
样例
给定 [-3, 1, 3, -3, 4], 返回[1,4].
解题思路:类似最大子数组的思路,需要注意的是索引合适改变,start在sum改变时改变,end一直改变,但是只在max发生改变时纪录下start和end。
一刷ac
public class Solution { /** * @param A an integer array * @return A list of integers includes the index of the first number and the index of the last number */ public ArrayList<Integer> continuousSubarraySum(int[] A) { ArrayList<Integer> res = new ArrayList<Integer>(); if(A == null || A.length == 0) return res; res.add(0); res.add(0); int sum = 0; int max = Integer.MIN_VALUE; int start = 0; int end = 0; for(int i = 0; i < A.length; i++){ if(sum < 0){ sum = A[i]; start = end = i; }else{ sum += A[i]; end = i; } if(max < sum){ max = sum; res.set(0, start); res.set(1, end); } } return res; } }
相关文章推荐
- LintCode: 连续子数组求和
- lintcode-402-连续子数组求和
- [LintCode] Continuous Subarray Sum 连续子数组之和
- 连续子数组求和
- 数组求和的艺术-一个数组最大连续字数组之和
- 连续子数组求和
- lintcode刷题--连续子数组求和
- LintCode : 连续子数组求和
- lintcode 中等题:continuous subarray sum 连续子数组之和
- 给定任意数组获取任意连续的项求和的最大值,并输出新的数组
- 连续子数组求和-LintCode
- 连续子数组求和
- 连续子数组求和
- JavaScript学习笔记之数组求和方法
- 面试题35:连续子数组的最大和
- 线性结构 -- 连续存储(数组), 1个简单的c语言代码实现.
- LintCode:177. 把排序数组转换为高度最小的二叉搜索树
- 求和最大的连续子串问题
- [C] 跨平台使用Intrinsic函数范例3——使用MMX、SSE2指令集 处理 32位整数数组求和
- 九度 题目1372:最大子向量和(连续子数组的最大和)