mediumDynamic ProgrammingPattern: DP
Maximize Subset Points Solution
Problem Statement
Given an array of integer weights and a capacity, determine the maximum weight subset that can be formed.
Examples
Example 1:
Input:[9,8,7,6,5]
Output:17
Explanation: The optimal subset would be [9, 8], which has a weight sum of 17.
Example 2:
Input:[7,3,4,5]
Output:13
Explanation: The optimal subset would be [5, 3, 5], which has a weight sum of 13.
Example 3:
Input:[1,2,4,2,5]
Output:7
Explanation: The optimal subset would be [4, 2, 1], which has a weight sum of 7.
Constraints
- Input array length is between 1 and 1000.
- Capacity is between 1 and 1000.
- Weights are non-negative integers.
Time: O(n*capacity) Space: O(n*capacity)
Use a dynamic programming approach to build up the maximum weight subset, with a time complexity of O(n*capacity) and a space complexity of O(n*capacity).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def max_subset_points(weights, capacity):
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, capacity + 1):
if weights[i - 1] > j: dp[i][j] = dp[i - 1][j]
else: dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weights[i - 1]] + weights[i - 1])
return dp[-1][-1]