Subsequence with difference of 1 (Memoization)

Given a list of numbers, find the longest subsequence such that the absolute difference between adjacent elements is 1.

Hint

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:

# Python implementation
cache = None

def count(ls, i, last):
  if i >= len(ls):
    return 0

  global cache
  if not cache:
    cache = [{} for _ in range(len(ls))]

  if last not in cache[i]:
    take = 0

    if i == 0 or abs(ls[i] - last) == 1:
      take = 1 + count(ls, i + 1, ls[i])

    skip = count(ls, i + 1, last)

    cache[i][last] = max(skip, take)
  
  return cache[i][last]

ls = [10, 9, 4, 5, 4, 8, 6]

print(count(ls, 0, 0))
// Javascript implementation
let cache = null;

function count(list, i, last) {
  if (i >= list.length) {
    return 0;
  }

  if (!cache) {
    cache = Array(list.length).fill({});
  }

  if (cache[i][last] === undefined) {
    let take = 0;
    if (i === 0 || Math.abs(list[i] - last) === 1) {
      take = 1 + count(list, i + 1, list[i]);
    }

    let skip = count(list, i + 1, last);

    cache[i][last] = Math.max(skip, take);
  }

  return cache[i][last];
}

const list = [10, 9, 4, 5, 4, 8, 6];

console.log(count(list, 0));