Skip to main content
Back to problems
#1043
Medium Algorithms

Partition array for maximum sum

Array Dynamic Programming
77.3% acceptance
Feb 25, 2026
5040
439
Given an integer array arr, 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. Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn max_sum_after_partitioning(arr: Vec<i32>, k: i32) -> i32 {
    let n = arr.len();
    let k = k as usize;
    let mut dp = vec![0i32; n + 1];
    for i in 1..=n {
      let mut cur_max = 0;
      for j in 1..=k.min(i) {
        cur_max = cur_max.max(arr[i - j]);
        dp[i] = dp[i].max(dp[i - j] + cur_max * j as i32);
      }
    }
    dp[n]
  }
}