LeetCode 2548: Maximum Price to Fill a Bag

ArrayGreedySorting

Problem Description

Explanation:

To solve this problem, we can use a dynamic programming approach. We create a 2D DP array where dp[i][j] represents the maximum price we can achieve using the first i items to fill a bag of capacity j. We iterate through each item and each capacity to fill the DP array. At each step, we have two choices: either include the current item in the bag or exclude it. If we include the item, we decrease the capacity by the item's weight and add the item's price to the total price. If we exclude the item, we move to the previous item without decreasing the capacity. We update the DP array based on these two choices. Finally, the maximum price to fill the bag is stored in dp[n][m], where n is the number of items and m is the bag's capacity.

Time complexity: O(nm), where n is the number of items and m is the bag's capacity. Space complexity: O(nm)

: :

Solutions

class Solution {
    public int maximumPrice(int[] prices, int[] weights, int n, int m) {
        int[][] dp = new int[n+1][m+1];
        
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (weights[i-1] <= j) {
                    dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-weights[i-1]] + prices[i-1]);
                } else {
                    dp[i][j] = dp[i-1][j];
                }
            }
        }
        
        return dp[n][m];
    }
}

Loading editor...