码迷,mamicode.com
首页 > 其他好文 > 详细

Continuous Subarray Sum

时间:2016-07-01 06:43:08      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

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)

Example

Give A = [-3, 1, 3, -3, 4], return [1,4].

分析:

max(i) = {max(i - 1) + A[i] if max(i - 1) >= 0, otherwise, A[i]}

 1 public class Solution {
 2     /**
 3      * @param A an integer array
 4      * @return  A list of integers includes the index of the first number and the index of the last number
 5      * cnblogs.com/beiyeqingteng/
 6      */
 7     public ArrayList<Integer> continuousSubarraySum(int[] A) {
 8         if (A == null || A.length == 0) return null;
 9         
10         ArrayList<Integer> list = new ArrayList<Integer>();
11         // initialization
12         int preMax = A[0];
13         int startIndex = 0;
14         int tempMax = A[0];
15         list.add(0);
16         list.add(0);
17         
18         for (int i = 1; i < A.length; i++) {
19             if (preMax < 0) {
20                 preMax = A[i];
21                 startIndex = i;
22             } else {
23                 preMax = A[i] + preMax;
24             }
25             // update
26             if (preMax > tempMax) {
27                 list.clear();
28                 list.add(startIndex);
29                 list.add(i);
30                 tempMax = preMax;
31             }
32         }
33         return list;
34     } 
35 }

转载请注明出处:cnblogs.com/beiyeqingteng/

 

Continuous Subarray Sum

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5631733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!