I am trying to add the squared elements for back into the original arraylist. For example [1,2,3] should become [1, 1, 2, 4, 3, 9]. My issue is I am not sure if my machine is just bad because I am getting an out of memory error. Here is my attempt. The recursive call is just to get the sum of the arraylist.
public static int sumOfSquares(List<Integer> num) {
if (num.isEmpty()) {
return 0;
}
for(int i=0; i<num.size();i++){
int hold= num.get(i)*num.get(i);
num.add(hold);
}
return num.get(0) + sumOfSquares(num.subList(1, num.size()));
}
The problem with your implementation is that it does not distinguish original numbers from the squares that you have previously added.
First, since you are doing this recursively, you don't need a for
loop. Each invocation needs to take care of the initial value of the list alone.
Next, add(n)
adds the number at the end, while your example shows adding numbers immediately after the original value. Therefore, you should use num.add(1, hold)
, and skip two initial numbers when making a recursive call.
Here is how the fixed method should look:
public static int sumOfSquares(List<Integer> num) {
if (num.isEmpty()) {
return 0;
}
// Deal with only the initial element
int hold= num.get(0)*num.get(0);
// Insert at position 1, right after the squared number
num.add(1, hold);
// Truncate two initial numbers, the value and its square:
return num.get(1) + sumOfSquares(num.subList(2, num.size()));
}