Sunday, October 21, 2012

Arrays3

Q3. You are given an array of integers (both positive and negative). Find the continuous sequence with the largest sum. Return the sum.
EXAMPLE
input: {2, -8, 3, -2, 4, -10}
output: 5 [ eg, {3, -2, 4} ]

Answer:

public class Arrays3 {
    public static int largestContinuousSum(int[] a) {
        int maxsum = 0;
        int sum = 0;

        for (int i = 0; i < a.length; i++) {
            sum += a[i];
            // if current sum is greater than maxsum then update maxsum
            if (sum > maxsum) {
                maxsum = sum;
            } else if (sum < 0) { // else if sum goes below zero reset sum and
                                  // start adding sum from new index
                sum = 0;
            }
        }
        return maxsum;
    }

    public static void main(String[] args) {
        int[] arr1 = { 2, -8, 3, -2, 4, -10 };
        int[] arr2 = { 6, -8, 3, -2, 4 };
        int[] arr3 = { -8, 6, 3, -2, 4 };

        System.out.println(largestContinuousSum(arr1));
        System.out.println(largestContinuousSum(arr2));
        System.out.println(largestContinuousSum(arr3));
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.