<p>Given an array <code>nums</code> of integers, return <em>the length of the longest arithmetic subsequence in</em> <code>nums</code>.</p>

<p><strong>Note</strong> that:</p>

<ul>
	<li>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</li>
	<li>A sequence <code>seq</code> is arithmetic if <code>seq[i + 1] - seq[i]</code> are all the same value (for <code>0 &lt;= i &lt; seq.length - 1</code>).</li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [3,6,9,12]
<strong>Output:</strong> 4
<strong>Explanation: </strong> The whole array is an arithmetic sequence with steps of length = 3.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [9,4,7,2,10]
<strong>Output:</strong> 3
<strong>Explanation: </strong> The longest arithmetic subsequence is [4,7,10].
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [20,1,15,3,10,5,8]
<strong>Output:</strong> 4
<strong>Explanation: </strong> The longest arithmetic subsequence is [20,15,10,5].
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>2 &lt;= nums.length &lt;= 1000</code></li>
	<li><code>0 &lt;= nums[i] &lt;= 500</code></li>
</ul>

def pprint_matrix(matrix):
    print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in matrix]))

class Solution:
    def longestArithSeqLength(self, nums: List[int]) -> int:
        """
        可以先分成遞增、遞減、不變 三種
        先只解遞增，
        sol 1: (X)
            先把 array 變成 prefix_max ?
            不行，因為又不一定要從 1st element 開始，這樣會漏掉
        sol 2: (?)
            DP ? 目前沒想到什麼好的 DP definition
            def dp[i][j] = 頭i 尾j？
            def dp[i][j] = prev i, cur j?
        sol 3: (X)
            next greater element (Monotonic Queue) ?
            不行，case3 會失敗
        sol 4: (?)
            two pointer ?
        """
        n = len(nums)
        value_id = {}  # record the "latest prev" id of the value
        dp = [{} for _ in range(n)]
        ans = 0
        for prev_id in range(n - 1):
            prev_value = nums[prev_id]
            for cur_id in range(prev_id + 1, n):
                cur_value = nums[cur_id]
                prev_prev_value = prev_value - (cur_value - prev_value)
                if prev_prev_value in value_id:
                    prev_prev_id = value_id[prev_prev_value]
                    res = 1 + dp[prev_prev_id][prev_id]
                else:
                    res = 2
                dp[prev_id][cur_id] = res
                ans = res if res > ans else ans
            value_id[prev_value] = prev_id
        return ans
46823