class Solution(object):
    def maxSumAfterPartitioning(self, A, K):
        """
        :type A: List[int]
        :type K: int
        :rtype: int
        """
        dp = [0 for _ in range(len(A))]
        
        for i, x in enumerate(A): #ɨÿ
            subarray_max = x
            for j in range(1, K + 1): # J ǰĳȣA[i], A[i - (j - 1): i + 1]
                if i - (j - 1) >= 0:#ǰⳤΪ J 飬
                    subarray_max = max(subarray_max, A[i - (j - 1)]) #ȷsubarray_maxǴֵ
                    #ôдsubarray_max = max(A[i - (j - 1): i + 1]]ҲԹǺ
                    
                    if i - j < 0:  # A[i]֮ǰǡj - 1Ԫأһ˳ΪJ飬൱ڵǰԱʾΪA[:j]
                        dp[i] = max(dp[i], subarray_max * j)
                    else:
                        dp[i] = max(dp[i], dp[i - j] + subarray_max * j)

        return dp[-1]