Partition Array for Maximum Sum in Python

The Partition Array for Maximum Sum problem involves partitioning an array into contiguous subarrays of length at most K, where each subarray's values are replaced with the maximum value in that subarray. The goal is to maximize the total sum after partitioning.

For example, with array [1, 15, 7, 9, 2, 5, 10] and K=3, the optimal partitioning creates subarrays [1, 15, 7], [9], and [2, 5, 10], which become [15, 15, 15], [9], and [10, 10, 10], giving sum 84.

Algorithm Approach

We use dynamic programming where dp[i] represents the maximum sum for the subarray ending at index i. For each position, we try all possible partition lengths (1 to K) and choose the one that gives the maximum sum.

Step-by-Step Solution

The algorithm follows these steps:

  • Create a DP array of the same length as the input array
  • For each position i, calculate the maximum sum by trying all valid partition sizes
  • For each partition size j, find the maximum element and calculate the potential sum
  • Update dp[i] with the maximum possible sum

Implementation

def maxSumAfterPartitioning(arr, k):
    n = len(arr)
    dp = [0] * n
    
    for i in range(n):
        # Initialize with single element partition
        dp[i] = arr[i] + (dp[i-1] if i-1 >= 0 else 0)
        max_val = arr[i]
        
        # Try all possible partition sizes from 1 to k
        for j in range(1, k):
            if i - j >= 0:
                index = i - j
                max_val = max(max_val, arr[i-j])
                partition_sum = max_val * (i - index + 1)
                prev_sum = dp[index-1] if index-1 >= 0 else 0
                dp[i] = max(dp[i], partition_sum + prev_sum)
    
    return dp[-1]

# Test the solution
arr = [1, 15, 7, 9, 2, 5, 10]
k = 3
result = maxSumAfterPartitioning(arr, k)
print(f"Array: {arr}")
print(f"K: {k}")
print(f"Maximum sum after partitioning: {result}")
Array: [1, 15, 7, 9, 2, 5, 10]
K: 3
Maximum sum after partitioning: 84

How It Works

Let's trace through the example step by step:

def maxSumAfterPartitioning_detailed(arr, k):
    n = len(arr)
    dp = [0] * n
    
    for i in range(n):
        print(f"\nProcessing index {i} (value: {arr[i]})")
        
        # Single element partition
        dp[i] = arr[i] + (dp[i-1] if i-1 >= 0 else 0)
        max_val = arr[i]
        print(f"  Single partition: {dp[i]}")
        
        # Try larger partitions
        for j in range(1, k):
            if i - j >= 0:
                index = i - j
                max_val = max(max_val, arr[i-j])
                partition_sum = max_val * (i - index + 1)
                prev_sum = dp[index-1] if index-1 >= 0 else 0
                new_sum = partition_sum + prev_sum
                
                print(f"  Partition size {j+1}: max={max_val}, sum={new_sum}")
                dp[i] = max(dp[i], new_sum)
        
        print(f"  Final dp[{i}] = {dp[i]}")
    
    return dp[-1]

# Detailed execution
arr = [1, 15, 7, 9, 2, 5, 10]
k = 3
result = maxSumAfterPartitioning_detailed(arr, k)
print(f"\nFinal result: {result}")
Processing index 0 (value: 1)
  Single partition: 1
  Final dp[0] = 1

Processing index 1 (value: 15)
  Single partition: 16
  Partition size 2: max=15, sum=30
  Final dp[1] = 30

Processing index 2 (value: 7)
  Single partition: 37
  Partition size 2: max=15, sum=45
  Partition size 3: max=15, sum=45
  Final dp[2] = 45

Processing index 3 (value: 9)
  Single partition: 54
  Partition size 2: max=9, sum=63
  Partition size 3: max=15, sum=60
  Final dp[3] = 63

Processing index 4 (value: 2)
  Single partition: 65
  Partition size 2: max=9, sum=63
  Partition size 3: max=9, sum=72
  Final dp[4] = 72

Processing index 5 (value: 5)
  Single partition: 77
  Partition size 2: max=5, sum=73
  Partition size 3: max=9, sum=90
  Final dp[5] = 90

Processing index 6 (value: 10)
  Single partition: 100
  Partition size 2: max=10, sum=83
  Partition size 3: max=10, sum=84
  Final dp[6] = 84

Final result: 84

Complexity Analysis

The time complexity is O(n × k) where n is the array length and k is the maximum partition size. The space complexity is O(n) for the DP array.

Conclusion

This dynamic programming solution efficiently finds the maximum sum by trying all valid partition sizes at each position. The key insight is that we can build the optimal solution incrementally by considering all possible ways to end each subarray.

Updated on: 2026-03-25T08:31:48+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements