Skip to content

Instantly share code, notes, and snippets.

@transparenceweb
Last active May 17, 2022 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save transparenceweb/cae578acfd84a2604ccf6a285088d2e3 to your computer and use it in GitHub Desktop.
Save transparenceweb/cae578acfd84a2604ccf6a285088d2e3 to your computer and use it in GitHub Desktop.
Solution for code challenge in issue #248 of rendezvous with cassidoo
const arr1 = [7, 4, 10, 0, 1];
const arr2 = [9, 7, 2, 3, 6];
const sortArr = (a, b) => {return b - a;};
const maximisedArray = function (arr1, arr2) {
const n = arr1.length;
const combinedArr = arr1.concat(arr2);
const sortedArr = combinedArr.sort(sortArr);
const uniqueElements = [...new Set(sortedArr)];
return uniqueElements.slice(0, n);
};
console.log(maximisedArray(arr1, arr2)); // [10, 9, 7, 6, 4]
@transparenceweb
Copy link
Author

transparenceweb commented May 17, 2022

Problem

Given two integer arrays of size n, return a new array of size n such that n consists of only unique elements and the sum of all its elements is maximum.

Example:

let arr1 = [7, 4, 10, 0, 1]
let arr2 = [9, 7, 2, 3, 6]
maximizedArray(arr1, arr2)
[9, 7, 6, 4, 10]

Thinking on solution

Did originally look at exactly matching output, drawing from arr1 then arr2 in specific order, but that wouldn’t generalise. So just kept it as a sorted list of uniques (to give maximum sum from unique values), then sliced that down to required length.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment