Partition Array for Maximum Sum in Python


Suppose we have an integer array A, we have to partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values changed to become the maximum value of that subarray. We have to find the largest sum of the given array after partitioning. So if input is like [1, 15, 7, 9, 2, 5, 10] and k = 3, then the output will be 84. This is because the array becomes [15, 15, 15, 9, 10, 10, 10]

To solve this, we will follow these steps −

  • make one array dp of length same as A, and fill this with 0
  • for i in range 0 to length of A - 1
    • dp[i] = A[i] + dp[i - 1] if i – 1 >= 0 otherwise 0
    • temp := A[i]
    • for j in range 1 to k – 1
      • if i – j >= 0
        • index := i – j
        • temp := max of temp and A[i - j]
        • if index – 1 >= 0, then
          • dp[i] := max of dp[i] and (temp*(i – index + 1) + dp[index - 1])
        • otherwise dp[i] := max of dp[i] and 0
  • return last element of dp

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def maxSumAfterPartitioning(self, A, K):
      dp = [0 for i in range(len(A))]
      for i in range(len(A)):
         dp[i] = A[i] + (dp[i-1] if i-1>=0 else 0)
         temp = A[i]
         for j in range(1,K):
            if i-j>=0:
               index = i-j
               temp = max(temp,A[i-j])
               dp[i] = max(dp[i],temp*(i-index+1) + (dp[index-1] if index-1 >=0 else 0))
      return dp[-1]
ob = Solution()
print(ob.maxSumAfterPartitioning([1,15,7,9,2,5,10],3))

Input

[1,15,7,9,2,5,10]
3

Output

84

Updated on: 30-Apr-2020

950 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements