LC 100327. 求出最长好子序列 II

https://leetcode.cn/problems/find-the-maximum-length-of-a-good-subsequence-ii/description/

维持两个最大长度。这题看了题解,觉得题解里面的写法很简洁,所以临摹了一版本。我的第一个版本其实思路是差不多的,但是感觉在写的时候其实信心不足。

class Solution:
    def maximumLength(self, nums: List[int], k: int) -> int:
        mx = [[0] * 3 for _ in range(k + 1)]
        fx = {}

        for x in nums:
            if x not in fx:
                fx[x] = [0] * (k + 1)
            f = fx[x]

            for kk in range(k, -1, -1):
                f[kk] += 1
                if kk > 0:
                    m = mx[kk - 1]
                    f[kk] = max(f[kk], (m[1] if m[2] == x else m[0]) + 1)
                    # f[kk] = max(f[kk], m[0] + 1)

                # update m
                v = f[kk]
                m = mx[kk]
                if v > m[0]:
                    if m[2] == x:
                        m[0] = v
                    else:
                        m[0], m[1], m[2] = v, m[0], x
                elif v > m[1] and m[2] != x:
                    m[1] = v

            # print(mx)

        return mx[k][0]