Find the largest adjacent sum of two numbers in a given array.
Note: Hope it helps you! Please note that all the intentions are to clear the doubt of how to solve it in java. So, please try to give it a chance at least before using this. If you face any discrepancy please contact us. Thank you!
Description:
Given an array of integers, find the pair of adjacent elements that has the largest sum and return that sum.
Example:
For array = [2, 5, 4, -2, -5, 7, 3]
,
The output should be
adjacentElementsSum(array) = 10
.
as 7
and 3
produce the largest Sum.
Solution:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class AdjacentElementsSum
{
public static void main (String[] args) throws java.lang.Exception{
AdjacentElementsSum q1 = new AdjacentElementsSum();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
for(int i = 0; i < array.length; i++){
array[i] = sc.nextInt();
}
System.out.println("Largest adjacent sum is: ");
System.out.println(q1.adjacentElementsSum(array));
}
int adjacentElementsSum(int[] array){
int max_sum = array[0]+array[1];
int n = array.length;
for(int i = 0; i < n-1; i++){
int temp = array[i]+array[i+1];
if(temp > max_sum){
max_sum = temp;
}
}
return max_sum;
}
}
Comments
Post a Comment