I've been working on a JavaScript function that counts the number of times two elements add up to a given sum. However, now I'm looking to modify this so that it not only considers when the two elements equal the sum, but also when they are less than or equal to the sum.
var array = [-10, -8, -1, 0, 1, 6, 10];
var sum = 16;
function findLessThanOrEqualSum(array, sum){
var count = 0;
var map = {};
for(var i = 0; i<array.length; i++){
var temp = sum - array[i]; //The current condition only handles cases when two elements equals the sum
if(temp >= 0 && map[temp]){
console.log(sum + " " + array[i] + " " + temp);
count++;
}
map[array[i]] = true;
}
console.log(count);
}
findLessThanOrEqualSum(array, sum);
Is there a way to adjust the condition var temp = sum - array[i];
so that it includes instances where temp
is less than or equal to sum - array[i];
?
I attempted creating a second variable for temp
to store values where temp <= sum - array[i];
, but have had no luck. Any guidance would be greatly appreciated.