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 === '<<') { if (currentComb.at(-1) < arr[i]) { currentComb.push(arr[i]); backtrack(i + 1, currentComb); currentComb.pop(); } } else if (command === '> >' || command === '>>') { if (currentComb.at(-1) > arr[i]) { 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 ]