和最大连续子数组

来源:互联网 发布:行知职业技术学校 编辑:程序博客网 时间:2024/05/22 11:45

给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的下标。(如果两个相同的答案,请返回其中任意一个)
给定 [-3, 1, 3, -3, 4], 返回[1,4].

数组无大于零元素

找出最大的负数即可

数组有大于零元素

标记非零元素起始下标,与后面元素进行累加,记为最大数组和,若和大于当前最大数组和,则标记元素结束下标.

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 class NSum{        int n;        int sum;        public NSum(int n,int sum){            this.n = n;            this.sum = sum;        }    }    public ArrayList<Integer> continuousSubarraySum(int[] A) {        // Write your code here        int Rb,Re,Max,tb,ts,MaxId;          Max = Integer.MIN_VALUE;          MaxId = Rb = Re = ts = tb = 0;          for(int i=0;i<A.length;++i){              ts += A[i];              if(ts < 0){                tb = i+1;                  ts = 0;              }else if(ts > Max){//更新最大和及其范围                  Rb = tb;                  Re = i;                  Max = ts;              }              if(A[i] > A[MaxId])                  MaxId = i;          }          if(Rb==0&&Re==0)              Rb = Re = MaxId;          ArrayList<Integer> R = new ArrayList<Integer>();          R.add(Rb);          R.add(Re);          return R;    }}
0 0
原创粉丝点击