714322. Maximum subset sum
Maximum Subset Sum
Summary
The Maximum Subset Sum problem is a classic dynamic programming problem where you are given an array of integers and need to find the maximum sum of a subset that can be obtained by selecting elements from the array. This problem involves dynamic programming concepts and requires a thorough understanding of how to break down complex problems into smaller sub-problems.
Detailed Explanation
The problem can be solved using dynamic programming, where you iterate over the array and calculate the maximum sum for each subset ending at each position. The key concept involved is memoization, where you store the calculated values in an array to avoid redundant calculations.
Here's a step-by-step breakdown of the solution:
- Initialize an array
dpof sizen+1, wherenis the length of the input array. Setdp[0] = 0. - Iterate over the array from left to right:
- For each element
arr[i], calculate the maximum sum for the subset ending at indexi. This can be done by considering two cases:- Case 1: Include the current element in the subset, which means adding
arr[i]to the maximum sum of the subset ending at indexi-1. - Case 2: Exclude the current element from the subset, which means using the same maximum sum as the subset ending at index
i-1.
- Case 1: Include the current element in the subset, which means adding
- Update
dp[i]with the maximum of these two cases.
- For each element
- The maximum subset sum is stored in
dp[n].
Here's an ASCII art diagram illustrating the dynamic programming approach:
arr[0] | dp[0]
arr[1] | dp[1] = max(0, arr[1])
arr[2] | dp[2] = max(dp[1], arr[2]) + arr[2]
...
arr[n-1] | dp[n-1] = max(dp[n-2], arr[n-1]) + arr[n-1]
arr[n] | dp[n] = max(dp[n-1], arr[n])
The time complexity of this solution is O(n), where n is the length of the input array. The space complexity is also O(n) for storing the dynamic programming table.
Optimized Solutions
Here are optimized solutions in various languages:
Java
public class MaximumSubsetSum {
public static int maxSubArraySum(int[] arr) {
int n = arr.length;
int[] dp = new int[n+1];
dp[0] = 0;
for (int i = 1; i <= n; i++) {
dp[i] = Math.max(dp[i-1], arr[i-1]);
if (i > 1) {
dp[i] = Math.max(dp[i], dp[i-1] + arr[i-1]);
}
}
return dp[n];
}
}