0

I have an Integer list, which has to be transformed into moving sum list: [ 1, 1, 1, 1, 1 ] => [ 1, 2, 3, 4, 5 ] [ 10, -10, 10, -10, 10 ] => [ 10, 0, 10, 0, 10 ]

But I'm struggling, how to set this up. Can anyone guide me through this?

public static List < Integer > getMovingSum(List < Integer > arr) {
    List < Integer > movingSumList = new List < Integer > ();
    movingSumList.add(arr[0]);
    for (Integer i = 0; i < arr.size(); i++) {

        Integer sum = movingSumList[i] + arr[i + 1];
        movingSumList.add(sum);
    }
    return movingSumList;
}

1 Answer 1

1

There is an issue in the loop exit. In case if i equals arr.size() - 1, it will still not exit the loop, but rather try to access i+1 element of an arr array, and that would cause an exception.

This is proper code

public static List < Integer > getMovingSum(List < Integer > arr) {
    List < Integer > movingSumList = new List < Integer > ();
    movingSumList.add(arr[0]);
    for (Integer i = 0; i < arr.size() - 1; i++) {
        Integer sum = movingSumList[i] + arr[i + 1];
        movingSumList.add(sum);
    }
    return movingSumList;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .