FunctionRacerProblemsRace

Pick With the Nearest Sum

HardTwo pointersPython, JavaScript, TypeScript, Java, C++

Pick any of the items of nums, from any positions; picking none of them is allowed and adds up to 0. Return how close the sum of a pick can come to goal: the smallest possible value of abs(sum - goal).

Example 1

nums [4,9,-3]
goal 7
returns 1

9 - 3 = 6 is one away from 7. No pick adds up to 7 itself.

Example 2

nums [10,20]
goal -5
returns 5

Picking nothing gives 0, which is 5 away. Any item only moves the sum further off.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Two pointers problems