RetailMeNot | SWE New Grad OA | Max Even Sum
Anonymous User
356

Given an array of integers A and an integer K, find a subsequence of length K such that the sum is the largest even sum possible. Return the sum, or -1 if no even sum can be made.

Example:

  • A = [4,2,6,7,8], K = 3 should return 18 as 4 + 6 + 8 = 18
  • A = [5, 5, 1, 1, 3], K = 3 should return -1

My approach was to create 2 arrays to hold the odd and even values and sort them in descending order. Then loop while k > 0. If k % 2 == 1 we take the next biggest even and add it to the result else if k % 2 == 0 we compare the sum of the next two odds and the next to evens and add the largest of the two sums to the result.

Time Complexity: O(N Log(N))
Space Complexity: O(N)

Comments (1)