712540. Partition Array for Maximum Sum

Medium

Partition Array for Maximum Sum

Summary

Given an array of integers, partition it into two subsets such that the maximum sum of the two subsets is achieved. The problem involves finding a way to divide the array elements into two groups where the sum of one group minus the sum of the other group (or vice versa) is maximized.

Detailed Explanation

To solve this problem, we can use dynamic programming. We first initialize an array dp of size n+1, where n is the length of the input array. The value at each position i in dp will represent the maximum sum that can be achieved by considering the first i elements of the array.

Here's a step-by-step breakdown of the solution:

  1. Initialize max_sum = 0 to keep track of the maximum sum found so far.
  2. Iterate through the input array from left to right:
    • For each element at index i, calculate the maximum sum that can be achieved by considering the first i elements and including or excluding the current element in the subset.
    • Update max_sum if a higher sum is found.
  3. Return max_sum.

Here's an ASCII art diagram representing the problem:

1 2 3 4 5
  |  |
  +---+

Time complexity: O(n) Space complexity: O(n)

Optimized Solutions

Java

View on GeeksforGeeks
int partitionArrayForMaximumSum(int[] arr) {
    int n = arr.length;
    int[] dp = new int[n+1];
    int max_sum = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++) {
            dp[i+1] = Math.max(dp[i], dp[i-j] + arr[j]);
        }
        max_sum = Math.max(max_sum, dp[i+1]);
    }

    return max_sum;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.