JSFiddle - React, Tailwind, and code Playground

Return highest sum of array elements divisible by n.

by Nalin Sajwan

JavaScript

let arr = [3, 6, 5, 1, 8];

let div = 3;

let allSums = [];
let allMatchesSums = [];

function subsetSums(arr, i, maxI, sum) {

	// Print current subset
	if (i > maxI) {

		// console.log("\n\nsum => ", sum);
    
    allSums.push(sum);

		if (sum % div === 0) {
			allMatchesSums.push(sum);
		}

		return;
	}

	// console.log("1. => ", sum); console.log("1. => ", arr[i]); console.log("1.",
	// sum + arr[i], i + 1, maxI); Subset including arr[i]
	subsetSums(arr, i + 1, maxI, sum + arr[i]);

	// console.log("2.", sum, i + 1, maxI); Subset excluding arr[i]
	subsetSums(arr, i + 1, maxI, sum);
}

subsetSums(arr, 0, arr.length - 1, 0);

allSums.sort((a, b) => {
	return b - a;
});

allMatchesSums.sort((a, b) => {
	return b - a;
});

console.log("allSums ==> ", allSums);
console.log("allMatchesSums ==> ", allMatchesSums);

let highest = allMatchesSums[0];

console.log("highest ==> ", highest);