is optimized a little bit. According to your algorithm, an array of n elements should be looped
.
n * n * in_arrayin_array
var arr = [1, 2, 5, 6, 7];//
var len =arr.length
let result=[]
let count=0
for(let a=0;a<len;aPP){
let max = arr.pop()
let newlen = arr.length
for(let i=0;i<newlen-1;iPP){
if(arr[i]+arr[i+1]> max){
break;
}
for(let j=i;j<newlen-1;jPP){
let plus = arr[i]+arr[j+1]
countPP
if(plus>max){
break;
}
if(plus==max){
result.push([max,arr[i],arr[j+1]])
}
}
}
}
console.log(result)//
console.log(count)//
As stated in the
reply, I did not consider the case of negative numbers. If you want to consider negative numbers, which maximum number pop will not work, you can only re-maintain a new array to enumerate all values. Modify as follows
var arr = [-8, -1, 1, 2, 5, 6, 7];//
var len =arr.length
var arr1 = [...arr] //
let result=[]
let count=0
for(let a=0;a<len;aPP){
let max = arr1.pop()//
let newlen = arr.length
for(let i=0;i<newlen-1;iPP){
if(arr[i]+arr[i+1]> max){
break;
}
for(let j=i;j<newlen-1;jPP){
let plus = arr[i]+arr[j+1]
countPP
if(plus>max){
break;
}
if(plus==max){
result.push([max,arr[i],arr[j+1]])
}
}
}
}
console.log(result)//
console.log(count)//
[[7, 1, 6], [7, 2, 5], [6, -1, 7], [6, 1, 5], [5, -1, 6], [1, -1, 2], [-1, -8, 7]]