Community Answer

Honor CodeSolved 1 Answer

See More Answers for FREE

Enhance your learning with StudyX

Receive support from our dedicated community users and experts

See up to 20 answers per week for free

Experience reliable customer service

Get Started

Code : #include <bits/stdc++.h> #include <iostream> using namespace std; int evenSumK(vector<int> arr, int N, int K) { if (K > N) return -1; int maxSum = 0; //make vector to stote even and odd number vector<int> Even; vector<int> Odd; //iterate all element and seprate each number in even and odd vector for(int i : arr) if (i % 2) Odd.push_back(i); else Even.push_back(i); //sort both even and odd vector sort(Odd.begin(), Odd.end()); sort(Even.begin(), Even.end()); //intialize index of last element from both list int i = Even.size() - 1; int j = Odd.size() - 1; //iterate while loop k times while (K > 0) { //check if k is odd or even if (K % 2 == 1) { if (i >= 0) { maxSum += Even[i]; i--; } else { return -1; } //decrement k by 1 K--; } //check that i and j is greater than or equal to 1 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; } //decrement k by 2 because here we added two number K -= 2; } else if (i >= 1) { //note : sum of two even number is also even so add it to maxSum maxSum += Even[i] + Even[i - 1]; i -= 2; K -= 2; } else if (j >= 1) { //note : sum of two odd number is always even so add it to maxSum maxSum += Odd[j] + Odd[j - 1]; j -= 2; K -= 2; } } //return maxSum return maxSum; } int main() { vector<int> A; A.push_back(4); A.push_back(9); A.push_back(8); A.push_back(2); A.push_back(6); int N = A.size(); int K = 3; cout << "Even sum : " << evenSumK(A, N, K) << endl; } Output : Even sum : 18 ...   ...