Looks like you are supposed to get to increasing or decreasing by 1, according to the given answers. So my first thoughts are, you need to scan to find the highest and which direction it's generally trending and add to elements, to get them all to the appropriate levels.
I'm working on a JS solution... We'll see where we end up. I'll edit this comment with it when done.
This is what I came up with... definitely not the best, but it seems to work with the given examples. I left in some commented code of some of the original trajectories I took.
function minimumAdditions(arr) {
// const diffs = [];
// for (let i = 1; i < arr.length; i++) {
// diffs[i - 1] = arr[i] - arr[i - 1];
// }
//
// console.dir(diffs);
//
// for (let i = diffs.length - 1; i > 0; i--) {
//
// }
//
// This approach is starting to look full of bugs, but back to it
// let max = arr.reduce((mx, val, index) => (
// val > mx.val ? { val, index } : mx
// ), { val: -Infinity, index: -1 });
//
// console.dir(max);
//
// This approach is shit too
// It looks like it would be easiest to find what the max should be
// and which end of the array it should be on... Then work from there.
// const left = arr[0];
// const right = arr[arr.length - 1];
//
// UGH, this is shit too... let's solve the first with diffs
const diffs = [];
for (let i = 1; i < arr.length; i++) {
diffs[i - 1] = arr[i] - arr[i - 1];
}
console.dir(diffs);
let direction = 0;
for (const diff of diffs) {
direction += diff > 0 ? 1 : -1;
}
if (direction < 0) {
arr.reverse();
}
let additions = 0;
let prevHeight = null;
for (let i = 0; i < arr.length; i++) {
let height = arr[i];
if (prevHeight !== null && height - prevHeight > 1) {
additions += (height - 1 - prevHeight) * i;
}
if (prevHeight !== null && height - prevHeight < 1) {
const newAdds = prevHeight + 1 - height;
height += newAdds;
additions += newAdds;
}
prevHeight = height;
}
console.log('additions:', additions);
return additions;
}
console.log(minimumAdditions([1, 4, 3, 2]) === 4);
console.log(minimumAdditions([2, 3, 2, 3]) === 4);
console.log(minimumAdditions([5, 7, 9, 4, 11]) === 9);