查找相邻元素的总和 - 方法和数组 [英] To find sum of adjacent elements - method and array
问题描述
给定一个整数数组,找到具有最大总和并返回该总和的相邻元素对
输入格式:
包含至少2个元素的整数数组
输出:
整数相邻元素的最大总和。
例子
对于inputArray = [3,6,-2,-5,7,3 ],输出应该是adjacentElementsSum(inputArray)= 10.
7和3产生最大的金额。
强制性:
1.使用以下两种方法创建Sample类:
2.方法细节:
a。方法名称= adajcentElementsSum()
b。 Access Specifier = public
c。 Argument =两个参数[数组元素和数组长度]类型为整数,在第一个测试用例中,数组元素为18,34,22,-19,31,-29,12,数组长度为7
d。返回类型=整数,它返回主方法的相邻元素的最大总和
3.访问示例中的adajcentElementsSum(int arr [],int n) 来自main方法类的类(TestClass)
注意:
方法定义的变量应为arr []和n public int adajcentElementsSum(int arr [],int n)
将方法中的sadjacentsum计算后的最大总和返回主方法
我的尝试:
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();
}
}
推荐答案
你的程序有几个错误。
例如方法签名是错误的。
我会开始编写正确的签名和空实现并修复应该调用它的main()
。 />
然后你可以专注于算法(它比你尝试传达的更简单)。
顺便说一句,你不需要TestClass
。将您的main方法移动到Sample
one。
Your program features several errors.
For instance the method signature is wrong.
I would start writing the correct signature and empty implementation and fixing themain()
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 theTestClass
. move your main method into theSample
one.
这篇关于查找相邻元素的总和 - 方法和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!