For example, in an array like [1,2,3,4,5], what numbers add up to 9?
The answers are 4 and 5, of course.
The next question is, what are the different ways we can write this program by comparing time complexity.
function addUpto(array,weight) { for(var i=0;i<array.length; i++) { for(var j=i+1; j<array.length; j++) { if(array[i]+array[j]==weight) { return [array[i],array[j]]; } } } return 'no matching'; } //To execute the above code, addUpto([1,2,3,4,5],9); //output is [4,5]
Comments
Post a Comment