LeetCode 2548: Maximum Price to Fill a Bag Solution

Master LeetCode problem 2548 (Maximum Price to Fill a Bag), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2548. Maximum Price to Fill a Bag

Problem Explanation

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)

: :

Solution Code

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];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2548 (Maximum Price to Fill a Bag)?

This page provides optimized solutions for LeetCode problem 2548 (Maximum Price to Fill a Bag) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2548 (Maximum Price to Fill a Bag)?

The time complexity for LeetCode 2548 (Maximum Price to Fill a Bag) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2548 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2548 in Java, C++, or Python.

Back to LeetCode Solutions