Q:

Multiplying values in array if same

I wanna write a recursive method that follows this logic:
suppose if the array is [3, 3, 3, 3] it will return a value of 30 because the consecutive number for trail[i] are equal to each other. So what happens here is 3 + (3 * 2) + (3 * 3) + (3 * 4) = 30
Another example is [2, 4, 3] it will return a value of 9
I hope this makes sense
Can anyone help?

A:

Why do you need recursion for this?
Simple loop should do the job:
public int sum(int[] arr) {
    int sum = 0;
    for (int i = 0, p = 0; i < arr.length; i++) {
        if (i == 0 || arr[i] == arr[i - 1]) {
            p++;
        } else {
            p = 1;
        }
        sum += arr[i] * p;
    }
    return sum;
}

update
Java 8 Stream API may be used to produce the same result:
public int sumStream(int[] arr) {
    int[] pp = {0};

    return IntStream.range(0, arr.length)
                    // update the quotient for the i-th element
                    .peek(i -> {
                        pp[0] = i == 0 || arr[i] == arr[i - 1] ? pp[0] + 1 : 1;
                    })
                    .map(i -> pp[0] * arr[i])
                    .sum();
}

