Click here to Skip to main content
14,766,632 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.


For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsSum(inputArray) = 10.

7 and 3 produce the largest sum.


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)

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.util.*;

class Sample
  Scanner s = new Scanner(;
 int n = s.nextInt();
  int i;
  int arr = new int[100];
 public int adjacentElementsSum()
   int largestsum=0;
   int previoussum=0;
   for(int i=0;i<=n;i++)
     for(int j=0;j<n;j++)
      int currentsum = previoussum - arr[i-1]+arr[i+n-1];
        largestsum = currentsum;
        previoussum = currentsum;
   return largestsum;
public class TestClass 
	 public static void main(String[] args)
       Sample obj = new Sample();
Updated 5-Feb-18 4:19am
Richard MacCutchan 5-Feb-18 9:11am
What is the question?

1 solution

Your program features several errors.
For instance the method signature is wrong.
I would start writing the correct signature and empty implementation and fixing the main() that should call it.
Then you may focus on the algorithm (it is simpler than your attemps convey).
By the way, you don't need the TestClass. move your main method into the Sample one.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900