two issues with this code
abs(target - ans) > abs(target - sum)
ans is initialized to 0, in the case (1,1,1,1) and target 3, this code would return 0 because abs(target-ans) and abs(target-sum) are always 0, always equal, so ans is returned as initial 0, never assigned.
another issue is overflow of the subtractions. I did not make these up but actually happened when I ran similar code in C++