Last active
May 17, 2022 19:25
-
-
Save transparenceweb/cae578acfd84a2604ccf6a285088d2e3 to your computer and use it in GitHub Desktop.
Solution for code challenge in issue #248 of rendezvous with cassidoo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problem
Given two integer arrays of size
n
, return a new array of sizen
such thatn
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.