Published
Edited
Apr 27, 2022
Insert cell
# Max points
Insert cell
function maxPoints(arr) {
let total = 0;

// Important to sort it from bigger to smaller to get maximum points
arr.sort((a, b) => b - a);

for (let i = 0; i < arr.length;) {
const [item, plusOne, minusOne] = [arr[i], arr[i] + 1, arr[i] - 1];

// If current value is no longer in the array just skip it
if (!arr.includes(item)) i++;

// Remove the first item in the array because is there
arr.shift();

// Check if the plus or minus one exist, if they exist remove it
if (arr.includes(plusOne)) arr.splice(arr.indexOf(plusOne), 1);
if (arr.includes(minusOne)) arr.splice(arr.indexOf(minusOne), 1);
total += item;
}

return total;
}
Insert cell
function maxPoints2(arr) {
let total = 0;

// We iterate as long as we have something in the array
while (arr.length > 0) {
// Get the biggest number every time
const max = Math.max(...arr);
const [item, plusOne, minusOne] = [max, max + 1, max - 1];

// Delete that number and their plus or minus one from the array
arr.splice(arr.indexOf(item), 1);
if (arr.includes(plusOne)) arr = arr.filter((i) => i !== plusOne);
if (arr.includes(minusOne)) arr = arr.filter((i) => i !== minusOne);

total += item;
}

return total;
}
Insert cell
maxPoints([5, 4, 6, 6, 11])
Insert cell
maxPoints2([5, 4, 6, 6, 11])
Insert cell
maxPoints2([10, 11, 10])
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more