Problem statement

https://binarysearch.com/problems/Copy-Paste/

Solution

Variation of Leetcode 0651 4 Keys Keyboard, but in fact we have 3 keys.

Complexity

It is O(N) for time and space.

Code

class Solution:
    def solve(self, N):
        if N == 0: return 0
        dp = [0] * (N+1)
        dp[1] = 1
        for i in range(2, N+1):
            dp[i] = max(dp[i-1] + 1, dp[i])
            for k in range(3, min(5, i-1)):
                dp[i] = max(dp[i], dp[i-k]*k)

        return dp[-1]