Given a list of numbers, find the longest subsequence such that the absolute difference between adjacent elements is 1.
This algorithm finds the longest sequence of numbers in a list where each number differs from its adjacent one by exactly 1. For each number in the list, consider two options:
Return the maximum length of all the subsequences found during the recursive exploration.
def count(ls, i, prev):
if i >= len(ls):
return 0
skip = count(ls, i + 1, prev)
take = 0
if prev == -1 or abs(ls[i] - ls[prev]) == 1:
take = 1 + count(ls, i + 1, i)
return max(skip, take)
ls = [10, 9, 4, 5, 4, 8, 6]
print(count(ls, 0, -1))
function count(list, i, prev) {
if (i >= list.length) {
return 0;
}
let skip = count(list, i + 1, prev);
let take = 0;
if (prev === -1 || Math.abs(list[i] - list[prev]) === 1) {
take = 1 + count(list, i + 1, i);
}
return Math.max(skip, take);
}
const list = [10, 9, 4, 5, 4, 8, 6];
console.log(count(list, 0, -1));