Skip to content
LC-1218 Medium LeetCode

1218. Longest Arithmetic Subsequence of Given Difference

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 54% Topics: Array, Hash Table, Dynamic Programming
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(n)

import collections


class Solution(object):
    def longestSubsequence(self, arr, difference):
        """
        :type arr: List[int]
        :type difference: int
        :rtype: int
        """
        result = 1
        lookup = collections.defaultdict(int)
        for i in xrange(len(arr)):
            lookup[arr[i]] = lookup[arr[i]-difference] + 1
            result = max(result, lookup[arr[i]])
        return result

Solution from kamyu104/LeetCode-Solutions · MIT