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)
Have you met this question in a real interview?
Yes
Example
Give [-3, 1, 3, -3, 4]
, return [1,4]
.
Tags Expand
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> list = new ArrayList<Integer>(); if(A == null || A.length <=0) return list; int sum = A[0]; int max = sum; int start =0 , end = 0; list.add(0); list.add(0); for(int i = 1 ; i < A.length ; i++){ if(sum > max){ list.set(0,start); list.set(1,i-1); max = sum; } if(sum < 0){ sum = 0; start = i; end = i; } sum += A[i]; } if(sum > max){ list.set(0,start); list.set(1,A.length -1); } return list; } }