Write a function named largestDifferenceOfEvens which returns the largest difference between even valued elements of its array argument. For example largestDifferenceOfEvens(new int[ ]{-2, 3, 4, 9}) returns 6 = (4 – (-2)). If there are fewer than 2 even numbers in the array, largestDifferenceOfEvens should return -1.
If you are programming in Java or C#, the function signature is
int largestDifferenceOfEvens(int[ ] a)
If you are programming in C or C++, the function signature is
int largestDifferenceOfEvens(int a[ ], int len) where len is the number of elements in the array a.
java 实现代码:
package com.zzy;
/**
* 更多请关注: http://huamaodashu.com
* Created by hadoopall on 10/08/2018.
*/
public class DifferenceOfEvens {
public static void main(String[] args) {
// int [] a = {1, 3, 5, 9};
// int [] a = {1, 18, 5, 7, 33};
// int [] a = {2, 2, 2, 2};
int [] a = {1, 2, 1, 2, 1, 4, 1, 6, 4};
System.out.println(largestDifferenceOfEvens(a));
}
public static int largestDifferenceOfEvens(int[] a){
int maxEven = 0;
int minEven = 0;
int count =0;
// for (int i = 0; i < a.length; i++) {
// if(isEven(a[i]) == 1){
// maxEven = a[i];
// minEven = a[i];
// break;
// }
// }
for (int i = 0; i < a.length; i++) {
if(isEven(a[i])==1){
if(count == 0){
maxEven = a[i];
minEven = a[i];
}
count++;
if(a[i] > maxEven){
maxEven = a[i];
}
if(a[i] < minEven){
minEven = a[i];
}
}
}
if(count < 2){
return -1;
}else {
return maxEven - minEven;
}
}
public static int isEven(int a){
if(a%2==0){
return 1;
}else {
return 0;
}
}
}