Skip to content

1.20 Largest Even Diff

Farrukh Ahmad edited this page Jan 4, 2016 · 1 revision

Lets returns the largest difference between elements of its array argument.

[-2, 3, 4, 9] returns 6 = (4 - (-2)).

If there are fewer than 2 even numbers in the array, return -111.

public class LargestEvenAbs {

public static void main(String[] args) {
	int a[]={-2, 3, 4, 9};
	System.out.println(largestEven(a));
}

static int largestEven(int a[])	{
	int diff = -111;

	for(int i=0; i<a.length; i++){
		for(int j=i+1; j<a.length-1; j++){
			if(a[i]%2==0 && a[j]%2==0){
				if(Math.abs(a[i]-a[j]) > diff)
					diff = Math.abs(a[i]-a[j]);
			}
		}
	}
	return diff;
}
}

Clone this wiki locally