Given an array of size n. The task is to find the longest subsequence such that absolute difference between adjacents is one.
Example 1:
Input : Arr[] = {10, 9, 4, 5, 4, 8, 6}
Output : 3
Explanation:
As longest subsequences with difference 1 
are, ("10, 9, 8"), ("4, 5, 4") and 
("4, 5, 6"). 
Example 2:
Input : Arr[] = {1, 2, 3, 2, 3, 7, 2, 1}
Output : 7
 
Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function longLenSub() that takes an array (arr), sizeOfArray (n), and return the length of the longest subsequence with absolute difference 1. The driver code takes care of the printing.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints: 
1 ≤ n, a[i] ≤ 10^{5}

Source: geeksforgeeks | Difficulty: EASY
Tags: Data structures

Starter code: #User function Template for python3

class Solution:
    def longLenSub(self, arr, n):
        #Complete the function

Solutions:
from collections import defaultdict

class Solution:

	def longLenSub(self, arr, n):
		store = defaultdict(lambda : 0)
		for item in arr:
			store[item] = max(store[item - 1], store[item + 1]) + 1
		return max(store.values())


from collections import defaultdict

class Solution:

	def longLenSub(self, arr, n):
		mx = 0
		d = defaultdict(int)
		for ele in arr:
			d[ele] = 1 + max(d[ele - 1], d[ele + 1])
			mx = max(mx, d[ele])
		return mx


class Solution:

	def longLenSub(self, arr, n):
		res = 0
		d = {}
		for i in arr:
			d[i] = 1
			if i - 1 in d:
				d[i] = max(d[i], d[i - 1] + 1)
			if i + 1 in d:
				d[i] = max(d[i], d[i + 1] + 1)
			res = max(res, d[i])
		return res


from collections import defaultdict

class Solution:

	def longLenSub(self, arr, n):
		um = defaultdict(lambda : 0)
		longLen = 0
		for i in range(n):
			len1 = 0
			if arr[i - 1] in um and len1 < um[arr[i] - 1]:
				len1 = um[arr[i] - 1]
			if arr[i] + 1 in um and len1 < um[arr[i] + 1]:
				len1 = um[arr[i] + 1]
			um[arr[i]] = len1 + 1
			if longLen < um[arr[i]]:
				longLen = um[arr[i]]
		return longLen


class Solution:

	def longLenSub(self, arr, n):
		counter = {}
		max_count = 0
		for el in arr:
			counter[el] = 1
			if el - 1 in counter:
				counter[el] = counter[el - 1] + 1
			if el + 1 in counter:
				counter[el] = max(counter[el], counter[el + 1] + 1)
			max_count = max(max_count, counter[el])
		return max_count


class Solution:

	def longLenSub(self, arr, n):
		result = 0
		dic = {}
		for i in arr:
			dic[i] = 1
			if i - 1 in dic:
				dic[i] = max(dic[i], dic[i - 1] + 1)
			if i + 1 in dic:
				dic[i] = max(dic[i], dic[i + 1] + 1)
			result = max(result, dic[i])
		return result