I have a homework. The homework is like that
There is the number X, and array A and array B whose data type is int. and I should find the A[I]+B[J](0<=I<=A.length, 0<=J<=B.length) which is closest to X.
First, I tried to find the answer by testing All I&J. but there is time limit and memory limit. So I made a hypothesis the number which is larger than X is not needed. However, I faced at the time limit exceed problem again. How can I save the time?
my code is this.
import java.util.Scanner;
import java.lang.Math;
public class PRO_D{
public static void main(String[] args)
{
Scanner kb=new Scanner(System.in);
int aLen=kb.nextInt();
int bLen=kb.nextInt();
long number=kb.nextLong();
long distance=100;
long dist=100;
int aCnt=0, bCnt=0;
long temp;
kb.nextLine();
long[] arrA=new long[aLen];
long[] arrB=new long[bLen];
for(int i=0; i<aLen; i++)
{
temp = kb.nextLong();
if (temp <= number)
{
if(number-temp<distance)
{
distance=number-temp;
}
arrA[i] = temp;
aCnt++;
}
else if(number-temp<distance)
{
arrA[i]=temp;
aCnt++;
}
}
for(int i=0; i<bLen; i++)
{
temp = kb.nextLong();
if (temp <= number)
{
if(number-temp<distance)
{
distance=number-temp;
}
arrB[i] = temp;
bCnt++;
}
else if(number-temp<distance)
{
arrB[i]=temp;
bCnt++;
}
}
for(int i=0; i<aCnt; i++)
for(int j=0; j<bCnt; j++)
{
temp=Math.abs(number-arrA[i]-arrB[j]);
if(dist>temp)
dist=temp;
}
System.out.println(dist);
}