Problem statement is find sum of each adjacent numbers and finally print second highest sum and two adjacent numbers from this came.
Condition - Only one loop.
public class AdjencentSumOfWithSecondHighest {
public static void main(String[] args) {
int[] arr = {2, 5, 3, 8, 9, 1, 7};
int[] newArr = new int[arr.length - 1];
int highest = arr[0], previoushighest = highest;
int index = 0, prevIndex = 0;
for (int i = 0; i < arr.length - 1; i++) {
newArr[i] = arr[i] + arr[i + 1];
if(highest < newArr[i]){
previoushighest = highest;
highest = newArr[i];
prevIndex = index;
index = i;
}
}
System.out.println("Second Highest NO : "+previoushighest);
System.out.println("no one is "+arr[prevIndex]+ " and no two is "+arr[index]);
}
}
Working very good. But if in array there is duplicate numbers then wrong result like {2, 5, 3, 3, 8, 9, 1, 7}