I found an interview practice question as stated in the title. Everything so far seems correct, however my if
and else-if
statements for comparing stored values of each sum are letting me down. If the largest sum is obtained from the FIRST TWO elements of the array, then it does not work. If they are anywhere else, then it does.
I thought I logically get why this is the case hence why I have an else-if
statement which I thought would fix it. The answer found is 51, but this is incorrect. It should be the FIRST TWO (100+50). I feel like my logic is failing me and any guidance would be great!
import java.util.ArrayList;
public class Main { //Qn is to find the largest sum of two consecutive numbers in an array
public Main() {}
private static int sum;
public static void main(String[] args) {
int[] intArray = new int[]{100, 50, 0, 50, 1, 0, 0};
ArrayList<Integer> sumArray = new ArrayList<>();
int sum;
int answer = 0;
for (int i = 0; i < (intArray.length - 1); i++) {
for (int j = 1; j < intArray.length; j++) {
sum = intArray[i] + intArray[j];
sumArray.add(sum);
}
}
for (int temp = 0; temp < (sumArray.size()-1); temp++) {
for (int temp1 = 1; temp1 < sumArray.size(); temp1++) {
if(sumArray.get(temp) > sumArray.get(temp1)){
answer = sumArray.get(temp);
}
else if (sumArray.get(temp) < sumArray.get(temp1)) {
answer = sumArray.get(temp1);
}
}
}
System.out.println(answer);
}
}
Actual answer = 51. Expected answer = 150.
That is a lot of code, and I'm not certain why you are comparing sumArray.get(temp)
with sumArray.get(temp1)
- you should compare with answer
; but honestly, we can simplify this.
Start by initializing answer
to the smallest possible value. Then iterate the array once and compare consecutive sums with the current answer
. Like,
int[] intArray = { 100, 50, 0, 50, 1, 0, 0 };
int answer = Integer.MIN_VALUE;
for (int i = 0; i < intArray.length - 1; i++) {
int sum = intArray[i] + intArray[i + 1];
answer = Math.max(answer, sum);
}
System.out.println(answer);
If using Java 8+, you could simplify it further by using a lambda to map the array values and stream that into max()
. Like,
int[] intArray = { 100, 50, 0, 50, 1, 0, 0 };
int answer = IntStream.range(0, intArray.length - 1)
.map(i -> intArray[i] + intArray[i + 1])
.max()
.orElse(Integer.MIN_VALUE);
System.out.println(answer);