1. Dynamic Programming

class Solution:
    def maxA(self, n: int) -> int:
        dp = list(range(n + 1))

        for i in range(n - 2):
            for j in range(i + 3, min(n, i + 6) + 1):
                dp[j] = max(dp[j], (j - i - 1) * dp[i])

        return dp[n]

Time & Space Complexity

  • Time complexity: O(n)O(n)

  • Space complexity: O(n)O(n)

Where nn is the maximum number of key presses allowed.