Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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.

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:

Java
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();
	}
}
Posted
Updated 25-Apr-22 1:18am
v2
Comments
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.
 
Share this answer
 

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