返回的数组应包含输入数组中具有最大总和的三个连续元素。而我被卡住了?有人帮忙吗?
public class Assigment4 {
public static void main(String[] args) {
int [] setOfNum= {1,2,3,4};
}
public static int [] threeIntegers (int [] numbers){
int [] arrayNew = new int [numbers.length-1];
int sum=0;
for(int i=0; i<3;i++){
sum=sum+numbers[i];
}
if (sum>)//i got stuck here
}
}
答案 0 :(得分:0)
我认为这应该有效。你需要两个循环
public static int [] threeIntegers (int [] numbers){
int max=0 //assuming array contains positive only
int [] maxArray = new int [3];
for(int j=0;j<numbers.length-2;++j){
int sum=0;
int [] newArray = new int [3];
for(int i=0; i<3;i++){
sum+=numbers[i+j];
newArray[i]=numbers[i+j];
}
if (sum>max){
max=sum;
maxArray=newArray;
}
}
return maxArray;
}
答案 1 :(得分:0)
public static int [] threeIntegers (int [] numbers){
int max=0;
int [] maxArray = null;
for(int i=0;i<numbers.length-3;++i)
{
int sum=numbers[i] + numbers[i+1] + numbers[i+2];
if (sum>max)
{
max=sum;
maxArray= new int[]{numbers[i], numbers[i+1], numbers[i+2]};
}
}
return maxArray;
}