Untitled
unknown
java
2 years ago
1.5 kB
28
Indexable
import java.util.Arrays;
class Solution {
public int solution(int[] A, int K) {
int N = A.length;
// Check if K is larger than N
if (K > N) {
return -1;
}
// Sort the array in non-decreasing order
Arrays.sort(A);
int sum = 0;
int count = 0;
// Iterate from the end of the sorted array
for (int i = N - 1; i >= 0; i--) {
if (A[i] % 2 == 0) { // If the element is even
sum += A[i];
count++;
}
// If we have selected K elements, break
if (count == K) {
break;
}
}
// If we couldn't find K even elements, return -1
if (count < K) {
return -1;
}
return sum;
}
}
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
// Test cases
System.out.println(solution.solution(new int[]{4, 9, 8, 2, 6}, 3)); // Output: 18
System.out.println(solution.solution(new int[]{5, 6, 3, 4, 2}, 5)); // Output: 20
System.out.println(solution.solution(new int[]{7, 7, 7, 7, 71}, 1)); // Output: -1
System.out.println(solution.solution(new int[]{10000}, 2)); // Output: -1
System.out.println(solution.solution(new int[]{2, 3, 3, 5, 5}, 3)); // Output: 12
}
}
Editor is loading...
Leave a Comment