How to find the maximum value we can achieve by picking k elements from an array in JavaScript

1 Answer

0 votes
function maxSumOfK(arr, k) {
  const sorted = [...arr].sort((a, b) => b - a); // descending
  
  return sorted.slice(0, k).reduce((sum, val) => sum + val, 0);
}

const arr = [11, 2, 4, 9, 3, 6, 5, 1];
const k = 3;

console.log(maxSumOfK(arr, k)); 



/*
run:
 
26
 
*/

 



answered Apr 6 by avibootz

Related questions

...