You are given an array A of N positive Integers and an Integer K.
Find the largest possible even sum of K elements at different
positions in A
For example given A = (4, 9, 8, 2, 6) and K = 3, the largest even sum
of three elements is 18. The three selected elements are Alo) - 4,
Al2 = 8 and A[4 - 6.
Write a function:
class Solution ( public int solution(int[] a, int k); }
that, given an array A of N positive Integers and positive Integer K,
returns the largest even sum of K elements. If there are no such K
elements, return -1.
Examples:
1. Given A - 14, 9, 8, 2, 6) and K -3, the function should return 18, as
explained above.
2. Given A - (5, 6, 3, 4, 2) and K-5, the function should return 20.
There are five elements and they sum to 20.
3. Given A-17.7,7,7,7) and K-1, the function should return -1, as
we can plak only one plement and there are no oven ones.
Answers
Answer:
please
Explanation:
mark me as brainliest
the largest possible even sum of K elements
Explanation:
#include <bits/stdc++.h>
using namespace std;
int solution(int arr[], int N, int K)
{
if (K > N) {
return -1;
}
int maxSum = 0;
vector<int> Even;
vector<int> Odd;
for (int i = 0; i < N; i++) {
if (arr[i] % 2) {
Odd.push_back(arr[i]);
}
else {
Even.push_back(arr[i]);
}
}
sort(Odd.begin(), Odd.end());
sort(Even.begin(), Even.end());
int i = Even.size() - 1;
int j = Odd.size() - 1;
while (K > 0) {
if (K % 2 == 1) {
if (i >= 0) {
maxSum += Even[i];
i--;
}else {
return -1;
}
K--;
}
else if (i >= 1 && j >= 1) {
if (Even[i] + Even[i - 1]
<= Odd[j] + Odd[j - 1]) {
maxSum += Odd[j] + Odd[j - 1];
j -= 2;
}
else {
maxSum += Even[i] + Even[i - 1];
i -= 2;
}
K -= 2;
}else if (i >= 1) {
maxSum += Even[i] + Even[i - 1];
i -= 2;
K -= 2;
}else if (j >= 1) {
maxSum += Odd[j] + Odd[j - 1];
j -= 2;
K -= 2;
}
}
return maxSum;
}
int main()
{
int arr[] = { 2, 4, 10, 3, 5 };
int N = sizeof(arr) / sizeof(arr[0]);
int K = 3;
cout << solution(arr, N, K)<<"\n";
int arr2[] = { 5, 6, 3, 4, 2};
N = sizeof(arr2) / sizeof(arr2[0]);
K = 5;
cout << solution(arr2, N, K)<<"\n";
int arr3[] = { 7,7,7,7,7 };
N = sizeof(arr3) / sizeof(arr3[0]);
K = 1;
cout << solution(arr3, N, K)<<"\n";
}