Skip to main content
1 of 3
  1. The solution above solves the above examples, but I challenge myself to find an example that my solution does not solve.

Here is one example, the expected reduction is 5, but the get_best function from the original post produces an actual reduction of 4, because it subtracts the last number...

{
    input: [5, 4, 3, 2, 1],
    output: { remaining: [5], reduction: 5 }
}

My test of examples proves the get_best function gets it wrong wrong:

... expected reduction is 5 with expected remaining 5,4,3,2,1 -- actual reduction is 4 with actual remaining 5,1

I can fix the get_bestfunction by adding one more else if check if the number would be subtracted, confirm it is not the last number from the original array A. If so, ignore it!

...
else if (i == A.length-1){
    console.log(`subtract: the current item is last in the list, contributes to net negative, ignoring the current item`);
} 
...