I found this interview question on some site and thought about it's solution.
The best solution I come to is to iterate over the whole array while saving the 4 biggest numbers and their indices.
After that I will need to find the biggest pair of these numbers ensuring that the selected numbers are not adjacent.
I think this ensures the correct solution to the question but I'm not sure it's the best solution.
My simple code is below.
Can someone give me a better idea to do this?
public int findMaxNonAdjacent(int [] array){
int big1=0, big2=0,big3=0,big4=0;
int i1=0,i2=0,i3=0,i4=0;
for(int i=0;i<array.length;i++)
{
if(array[i]>=big1){
big4=big3;
big3=big2;
big2=big1;
big1=array[i];
i4=i3;
i3=i2;
i2=i1;
i1=i;
}else if(array[i]>=big2){
big4=big3;
big3=big2;
big2=array[i];
i4=i3;
i3=i2;
i2=i;
}else if(array[i]>=big3){
big4=big3;
big3=array[i];
i4=i3;
i3=i;
}else if(array[i]>=big3){
big4=array[i];
i4=i;
}
}
if(Math.abs(i1-i2)>1)
return big1+big2;
else if(Math.abs(i1-i3)>1){
return big1+big3;
}else if((big1+big4>=big2+big3) &&(Math.abs(i1-i4)>1)){
return big1+big4;
}else if((big1+big4<=big2+big3) &&(Math.abs(i2-i3)>1)){
return big2+big3;
} else
return big3+big4;
}
Using 1-based indexing; Find the index of the biggest element in the array. If it's 1
, then find the biggest in the range [3, n]
and return it's sum. If the biggest is at index n
, then find the biggest in the range [1, n-2]
and return it's sum. Else if the index of the biggest is i
, then find the index of the biggest in [1, i-2]
and the index of the biggest in [i+2, n]
. Let them be l
and r
respectively. Then the answer will be max(A[i-1] + A[i+1], A[i] + max(A[l], A[r]))
.
Why do you want to keep 4 indices in your code? In my opinion, only 3 elements are sufficient according to pigeonhole principle. Another thing is to check if the input array has less than 3 elements because it's an invalid input.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.