Given a list of numbers, find the longest subsequence such that the absolute difference between adjacent elements is 1.
This algorithm uses memoization to improve performance. It's same as the recursive version of Subsequence with difference of 1, but with a special 'cache' to store results. The 'cache key' is crucial. It's how we identify and store past results. Sometimes we need one key, sometimes multiple keys. We add code to:
cache = None
def count(ls, i, prev):
if i >= len(ls):
return 0
global cache
if not cache:
cache = [{} for _ in range(len(ls))]
if prev not in cache[i]:
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)
cache[i][prev] = max(skip, take)
return cache[i][prev]
ls = [10, 9, 4, 5, 4, 8, 6]
print(count(ls, 0, -1))
let cache = null;
function count(list, i, prev) {
if (i >= list.length) {
return 0;
}
if (!cache) {
cache = Array(list.length).fill({});
}
if (cache[i][prev] === undefined) {
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);
}
cache[i][prev] = Math.max(skip, take);
}
return cache[i][prev];
}
const list = [10, 9, 4, 5, 4, 8, 6];
console.log(count(list, 0, -1));