I need to find the highest possible sum of numbers in an array passed to a function that can be divided with no remainder.
I am struggling to think of a way of iterating through an array of elements adding up all the possibilities and dividing by the parameter k
which is the number for the division.
I thought of using a for loop and then passing the result to a variable on each iteration.
The part I can't get my head around is how to add all the possible combinations of the numbers in the array. As I can add them sequentially from the start of the array to the last element but not in all combinations such as element at index 0
, element at index 3
etc.
I am fairly new to coding, explanations of how you could tackle the iteration challenge I have would be much appreciated.
function luckyCandies(prizes, k) {
let sum = 0;
let remainder = 0;
let maxCandies = 0;
let highestNumber = 0;
prizes.sort(function(a, b) {
return b - a;
});
for (let i = 0; i < prizes.length; i ) {
sum = sum prizes[i];
}
for (let i = 0; i < prizes.length; i ) {
if (sum % k == 0) {
sum = sum - prizes[i];
}
}
console.log(sum);
return sum;
}
CodePudding user response:
Implemented this solution for your use case based on the answers in this.
In the given link the solutions are for the highest possible sum of numbers given the divisible 3
but it won't be a problem since there is a proper in detailed explanation.
const maxSumDivByNo = (A, no) => {
const K = Array(no).fill().map((v,i) => 0);
for (let x of A) {
let pre = [...K]; // create current from previous