Wednesday, March 30, 2011

WAP Find Minimum In Difference betwen Two Array..Its Different Question,Have A Closer Look

Consider two non-empty zero-indexed arrays A and B consisting of N integers each. Four functions are defined based on these arrays:

F(X,K) = A[K]*X + B[K]
U(X) = max { F(X,K) : 0 <= K < N }
D(X) = min { F(X,K) : 0 <= K < N }
S(X) = U(X) - D(X)

Write a function

double minfuds(int[] A, int[] B);

that given two arrays A and B returns the minimum value of S(X) where X can be any real number. Assume that the arrays have equal length and that it does not exceed 100,000. Assume that each element of the arrays is an integer in range [-1,000..1,000].

For example, given arrays A and B such that

A[0] = -1 B[0] = 3
A[1] = 1 B[1] = 0
A[2] = 0 B[2] = 2

the function should return 0.5 because

U(X) = -1*X + 3 if X <= 1
U(X) = 0*X + 2 if 1 < X <= 2
U(X) = 1*X + 0 if 2 < X

and

D(X) = 1*X + 0 if X <= 1.5
D(X) = -1*X + 3 if 1.5 < X

so for X = 1.5 function S(X) is equal to 0.5 and this is the minimum value of this function.


class array
{
static double minfuds ( double [] a, double [] b )
{
double x=1.5;
double c[]=new double[a.length];
for(int i=0;i {
c[i]=a[i]*x+b[i];
}
double min=1000.0;
double max=-1000.0;
for(int j=0;j {
if(c[j]>max)
max=c[j];

if(c[j] min=c[j];
// write your code here
}

return (max-min);

}


public static void main(String a[])
{

System.out.println(minfuds(new double []{-1, 1, 0},new double []{3, 0, 2}));

}
}

Run Here https://ideone.com/Qo9Kc

No comments :