I was asked this question in an interview.Asked me to sum an Integer Array like Fibonacci series type.
Like if we add array[]={2,6,3,1}
output should be 31.
2+6=8, 8+3=11, 11+1=12, now add 8+11+12 = 31?
How can I do this in Java?
I was asked this question in an interview.Asked me to sum an Integer Array like Fibonacci series type.
Like if we add array[]={2,6,3,1}
output should be 31.
2+6=8, 8+3=11, 11+1=12, now add 8+11+12 = 31?
How can I do this in Java?
This was fun! The easiest solution to come up with is to use nested for
s and iterate over adding only if the previous value.
However, if we think about it, your example is linear, couldn't it be done in linear? Yes it could. So we now know we have to use only one (nested) for
. We have to keep track of the values that we've added together, in your example {2,6}
, {2,6,3}
and {2,6,3,1}
, so we can use a another Array
for that with a size one less than the input Array
.
However, can't we add them directly? Instead of storing every value we calculate we just store the previous one and the sum so far, the result:
public static int arrFibSum (int arr[]) {
int sum = 0;
for (int i = 0; i < arr.length-1; i++) {
sum += sum + arr[i+1];
}
return sum;
}
It takes an Array
, like yours {2,6,3,1}
Sets the previous value, to the last calculated value.
Calculate the next value based on the previous and the next.
In this example it prints out: 31
.
For the future: Try to write some psuedo-code. You wrote down one example try to write it generic and finally you are ready to start to implement it.
There is a reason why I tried to write the process step by step above.
Updated from Erik's comment.