Given a list of numbers, find the longest subsequence such that the absolute difference between adjacent elements is 1.
Building upon understanding of Subsequence with difference of 1 (Memoization). Pay attention to the cache. Tabulation essentially reconstructs the cache.
Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.
The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.
def count(ls): cache = {} mx = 1 for i in range(len(ls)): if ls[i] + 1 in cache or ls[i] - 1 in cache: cache[ls[i]] = 1 + max(cache.get(ls[i] + 1, 0), cache.get(ls[i] - 1, 0)) else: cache[ls[i]] = 1 mx = max(mx, cache[ls[i]]) return mx ls = [10, 9, 4, 5, 4, 8, 6] print(count(ls))
function count(list) { const cache = {} let max = 1; for (let i = 0; i < list.length; i++) { if (cache[list[i] + 1] != undefined || cache[list[i] - 1] != undefined) { cache[list[i]] = 1 + Math.max(cache[list[i] + 1] ? cache[list[i] + 1] : 0, cache[list[i] - 1] ? cache[list[i] - 1] : 0); } else { cache[list[i]] = 1; } max = Math.max(max, cache[list[i]]) } return max; } const list = [10, 9, 4, 5, 4, 8, 6]; console.log(count(list, 0));