0% completed
Js solution needs some corrections
Daniil
Dec 18, 2023
In solution by JavaScript i found some initial parameters, with which solution becomes incorrect. This parameters are: Input: [91, 74, 73, 85, 73, 81, 87], target: 230. Current solution returns 231, which is not right because it is bigger than target. Replacing this fragment from solution:
if (Math.abs(target_diff) < Math.abs(smallest_difference) ||
(Math.abs(target_diff) === Math.abs(smallest_difference) &&
target_diff > smallest_difference)) {
smallest_difference = target_diff; // save the closest and the biggest difference
}
with this fragment:
if (
targetDiff >= 0 &&
(Math.abs(targetDiff) < Math.abs(smallestDifference) || (
Math.abs(targetDiff) === Math.abs(smallestDifference) && targetDiff > smallestDifference
))) {
smallestDifference = targetDiff;
}
makes final result more correct. The difference is in this condition: targetDiff >= 0
0
0
Comments
Salah Osman2 years ago
The original function aimed to find the closest sum to the target sum, either greater or smaller. Your modified change, focuses on finding the closest sum that is not greater than the target sum.
Running your change gives 228 but the original solution provides 231 and...
On this page
Problem Statement
Try it yourself