function longestComb(arr, command){
const result = [];
function backtrack(startIndex, currentComb) {
console.log('currentComb', currentComb)
if (startIndex >= arr.length - 1) {
if (currentComb.length >= 3) {
result.push(currentComb.slice());
}
return;
} else {
if (currentComb.length >= 3) {
result.push(currentComb.slice());
}
}
for (let i = startIndex; i < arr.length; i++) {
if (!currentComb.length) {
currentComb.push(arr[i]);
backtrack(i + 1, currentComb);
currentComb.pop()
} else {
if (command === '< <' || command === '<<') {
currentComb.push(arr[i]);
backtrack(i + 1, currentComb);
currentComb.pop();
}
} else if (command === '> >' || command === '>>') {
currentComb.push(arr[i])
backtrack(i + 1, currentComb);
currentComb.pop();
}
}
}
}
}
backtrack(0, []);
if (!result.length) {
return result;
}
console.log(result)
const mappedToLength = result.map(el => el.length); const longestLength = Math.max(...mappedToLength);
const filteredResult = result.filter(el => el.length === longestLength);
return filteredResult.length > 1 ? filteredResult : filteredResult[0];
}
let arr = [-1, 3, -34, 18, -55, 60, 118, -64];
let comm = '< <';
console.log('#1', longestComb(arr, comm)); // [-1, 3, 18, 60, 118]
arr = [-1, 3, -34, 18, -55, 60, 118, -64];
comm = '> >';
console.log('#2', longestComb(arr, comm)) // [3, -34, -55, -64]]);
arr = [-26, 26, -36, 17, 12, 12, -10, -21];
comm = '< <';
console.log('#3', longestComb(arr, comm)) // []
arr = [
36, 26, -26, -40,
12, 27, -56, 34,
-55
]
comm = '> >';
console.log('#4', longestComb(arr, comm)) // [ [ 36, 26, -26, -40, -56 ], [ 36, 26, -26, -40, -55 ] ]
arr = [
45, 25, -19, 7, 46,
-19, 36, -50, -57, 26,
46, 50, 20
];
comm = '>>';
console.log('#5', longestComb(arr, comm)) // [ 45, 25, 7, -19, -50, -57 ]
arr = [
-31, 35, 1, -37, -1,
55, -40, 12, 8, -38,
12, -59
]
comm = '>>';
console.log('#6', longestComb(arr, comm))
arr [
59, -15, 34, -44,
-50, 49, -55, -18,
13
];
comm = '<<';
console.log('#7', longestComb(arr, comm))
// expected [ -15, 34, 49 ] to deeply equal [ [ -15, 34, 49 ], [ -44, -18, 13 ], [ -50, -18, 13 ], [ -55, -18, 13 ] ]