You are given an array of integers both positive and negative integers.Find the continuous sequence with largest sum.

For Example:

Input:-{2,-8,3,-2,4,-10}

Output:-5(i.e {3,-2,4})

```
/**
*
*/
/**
* @author Dixit
*
*/
public class LargestSumSequence {
/**
* @param args
*/
public static void main(String[] args) {
int a[]={2, -8, 3, -2, 4, -10};
System.out.println("Continuous sequence with Largest sum :"+getMaxSum(a));
}
public static int getMaxSum(int[] a) {
int maxsum = 0;
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
if (maxsum < sum) {
maxsum = sum;
} else if (sum < 0) {
sum = 0;
}
}
return maxsum;
}
}
```

```
Output:-
Continuous sequence with Largest sum :5
```

Enjoy Programming

I dont think the answer is 5 here.

ReplyDeleteIn this case, the largest sum is: 15 i.e. {3,-2,4,10}

Thanks for the correction. Here the input value is {2,-8,3,-2,4,-10} not {2,-8,3,-2,4,10}.

DeleteSo it displays 5 as the result.