Given an array of integers, find the pair of adjacent elements that has the largest sum and return that sum
Input Format:
An array of integers containing at least 2 elements
Output :
An integer The largest sum of adjacent elements.
Example
For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsSum(inputArray) = 10.
7 and 3 produce the largest sum.
Mandatory:
1. Create a class "Sample" with two following method:
2. Method Details:
a. Method Name = adajcentElementsSum ()
b. Access Specifier = public
c. Argument = Two arguments [Array elements and array length] of type integer , In first test- case the array elements are 18,34,22,-19,31,-29,12 and array length is 7
d. Return type = integer , It returns the largest sum of adjacent elements to the main method
3. Access the adajcentElementsSum(int arr[],int n) in "Sample" class from main method class (TestClass)
Note:
The method definition should have variables as "arr[]" and "n" public int adajcentElementsSum(int arr[],int n)
Return the largest sum after calculating sadjacentsum in the method to the main method
What I have tried:
import java.io.*;
import java.util.*;
class Sample
{
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int i;
int arr = new int[100];
for(i=0;i<n;i++)
{
arr[i]=s.nextInt();
}
public int adjacentElementsSum()
{
int largestsum=0;
int previoussum=0;
for(int i=0;i<=n;i++)
{
if(i==0)
{
for(int j=0;j<n;j++)
{
largestsum=largestsum+arr[j];
}
previoussum=largestsum;
}
else
{
int currentsum = previoussum - arr[i-1]+arr[i+n-1];
{
if(currentsum>largestsum)
{
largestsum = currentsum;
}
previoussum = currentsum;
}
}
}
return largestsum;
}
}
public class TestClass
{
public static void main(String[] args)
{
Sample obj = new Sample();
obj.adjacentElementsSum();
}
}