ank*_*ave 2 java arrays java-8
我有一个小问题,就是从java中的数组中找到最大偶数和。例如:在数组 {1,2,3,4,5,6} 中,最大偶数和应为 6(1+2+3),10( 中的 16(1+2+3+4+6) 1+2+3+4) 和 16。
但到目前为止,我得到 10 作为输出,因为它将 sum 作为连续的总和。请帮我解决一下。
感谢您将使用数组中所有元素的总和执行两件事之一。如果总和是偶数,则返回该数字,但如果是奇数,则必须删除一个数字才能使其成为偶数。请注意,删除偶数将使剩余的总和为奇数,因此删除偶数是没有意义的。但是,由于总和为奇数,因此数组中必须至少有一个奇数。
因此,如果总和为奇数,您所需要做的就是迭代数组并删除最小的奇数。并且保证至少有一个奇数。
这是一个实现:
public int findMaxEvenSum(int[] array) {
int total = 0;
for (int i=0; i < array.length; ++i) {
total += array[i];
}
if (total % 2 == 0) {
return total;
}
// otherwise iterate over the array and remove the smallest odd
// number from the sum
int lastOdd = 0;
for (int i=0; i < array.length; ++i) {
if (array[i] % 2 == 1 && (lastOdd == 0 || array[i] < lastOdd)) {
total += lastOdd;
total -= array[i];
lastOdd = array[i];
}
}
return total;
}
Run Code Online (Sandbox Code Playgroud)