Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
Java Program for Min Cost Path
Next article icon

Java Program 0-1 Knapsack Problem

Last Updated : 09 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Write a Java program for a given N items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. 

Examples:

Input: N = 3, W = 4, profit[] = {1, 2, 3}, weight[] = {4, 5, 1}
Output: 3
Explanation: There are two items which have weight less than or equal to 4. If we select the item with weight 4, the possible profit is 1. And if we select the item with weight 1, the possible profit is 3. So the maximum possible profit is 3. Note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4.

Input: N = 3, W = 3, profit[] = {1, 2, 3}, weight[] = {4, 5, 6}
Output: 0

Java Program for 0-1 Knapsack Problem using Recursion:

A simple solution is to consider all subsets of items and calculate the total weight and profit of all subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets, pick the subset with maximum profit.

Optimal Substructure: To consider all subsets of items, there can be two cases for every item. 

  • Case 1: The item is included in the optimal subset.
  • Case 2: The item is not included in the optimal set.

Step-by-step approach:

The maximum value obtained from ‘N’ items is the max of the following two values. 

  • Case 1 (include the Nth item): Value of the Nth item plus maximum value obtained by remaining N-1 items and remaining weight i.e. (W-weight of the Nth item).
  • Case 2 (exclude the Nth item): Maximum value obtained by N-1 items and W weight.
  • If the weight of the ‘Nth‘ item is greater than ‘W’, then the Nth item cannot be included and Case 2 is the only possibility.

Below is the implementation of the above approach:

Java




/* A Naive recursive implementation
of 0-1 Knapsack problem */
class Knapsack {
 
    // A utility function that returns
    // maximum of two integers
    static int max(int a, int b) { return (a > b) ? a : b; }
 
    // Returns the maximum value that
    // can be put in a knapsack of
    // capacity W
    static int knapSack(int W, int wt[], int val[], int n)
    {
        // Base Case
        if (n == 0 || W == 0)
            return 0;
 
        // If weight of the nth item is
        // more than Knapsack capacity W,
        // then this item cannot be included
        // in the optimal solution
        if (wt[n - 1] > W)
            return knapSack(W, wt, val, n - 1);
 
        // Return the maximum of two cases:
        // (1) nth item included
        // (2) not included
        else
            return max(val[n - 1]
                        + knapSack(W - wt[n - 1], wt,
                                    val, n - 1),
                    knapSack(W, wt, val, n - 1));
    }
 
    // Driver code
    public static void main(String args[])
    {
        int profit[] = new int[] { 60, 100, 120 };
        int weight[] = new int[] { 10, 20, 30 };
        int W = 50;
        int n = profit.length;
        System.out.println(knapSack(W, weight, profit, n));
    }
}
/*This code is contributed by Rajat Mishra */
 
 
Output
220 

Time Complexity: O(2N)
Auxiliary Space: O(N), Stack space required for recursion

Java Program for 0-1 Knapsack Problem using Dynamic Programming:

Memoization Approach for 0/1 Knapsack Problem:

If we get a subproblem the first time, we can solve this problem by creating a 2-D array that can store a particular state (n, w). Now if we come across the same state (n, w) again instead of calculating it in exponential complexity we can directly return its result stored in the table in constant time.

Below is the implementation of the above approach:

Java




// Here is the top-down approach of
// dynamic programming
 
import java.io.*;
 
class GFG {
 
    // A utility function that returns
    // maximum of two integers
    static int max(int a, int b) { return (a > b) ? a : b; }
 
    // Returns the value of maximum profit
    static int knapSackRec(int W, int wt[], int val[],
                        int n, int[][] dp)
    {
 
        // Base condition
        if (n == 0 || W == 0)
            return 0;
 
        if (dp[n][W] != -1)
            return dp[n][W];
 
        if (wt[n - 1] > W)
 
            // Store the value of function call
            // stack in table before return
            return dp[n][W]
                = knapSackRec(W, wt, val, n - 1, dp);
 
        else
 
            // Return value of table after storing
            return dp[n][W]
                = max((val[n - 1]
                    + knapSackRec(W - wt[n - 1], wt, val,
                                    n - 1, dp)),
                    knapSackRec(W, wt, val, n - 1, dp));
    }
 
    static int knapSack(int W, int wt[], int val[], int N)
    {
 
        // Declare the table dynamically
        int dp[][] = new int[N + 1][W + 1];
 
        // Loop to initially filled the
        // table with -1
        for (int i = 0; i < N + 1; i++)
            for (int j = 0; j < W + 1; j++)
                dp[i][j] = -1;
 
        return knapSackRec(W, wt, val, N, dp);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int profit[] = { 60, 100, 120 };
        int weight[] = { 10, 20, 30 };
 
        int W = 50;
        int N = profit.length;
 
        System.out.println(knapSack(W, weight, profit, N));
    }
}
 
// This Code is contributed By FARAZ AHMAD
 
 
Output
220 

Time Complexity: O(N * W). As redundant calculations of states are avoided.
Auxiliary Space: O(N * W) + O(N). The use of a 2D array data structure for storing intermediate states and O(N) auxiliary stack space(ASS) has been used for recursion stack

Bottom-up Approach for 0/1 Knapsack Problem:

Since subproblems are evaluated again, this problem has Overlapping Sub-problems property. So the 0/1 Knapsack problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computation of the same subproblems can be avoided by constructing a temporary array K[][] in a bottom-up manner. 

Below is the implementation of the above approach:

Java




// A Dynamic Programming based solution
// for 0-1 Knapsack problem
 
import java.io.*;
 
class Knapsack {
 
    // A utility function that returns
    // maximum of two integers
    static int max(int a, int b) { return (a > b) ? a : b; }
 
    // Returns the maximum value that can
    // be put in a knapsack of capacity W
    static int knapSack(int W, int wt[], int val[], int n)
    {
        int i, w;
        int K[][] = new int[n + 1][W + 1];
 
        // Build table K[][] in bottom up manner
        for (i = 0; i <= n; i++) {
            for (w = 0; w <= W; w++) {
                if (i == 0 || w == 0)
                    K[i][w] = 0;
                else if (wt[i - 1] <= w)
                    K[i][w]
                        = max(val[i - 1]
                                + K[i - 1][w - wt[i - 1]],
                            K[i - 1][w]);
                else
                    K[i][w] = K[i - 1][w];
            }
        }
 
        return K[n][W];
    }
 
    // Driver code
    public static void main(String args[])
    {
        int profit[] = new int[] { 60, 100, 120 };
        int weight[] = new int[] { 10, 20, 30 };
        int W = 50;
        int n = profit.length;
        System.out.println(knapSack(W, weight, profit, n));
    }
}
/*This code is contributed by Rajat Mishra */
 
 
Output
220 

Time Complexity: O(N * W). where ‘N’ is the number of elements and ‘W’ is capacity. 
Auxiliary Space: O(N * W). The use of a 2-D array of size ‘N*W’.

Space optimized Approach for 0/1 Knapsack Problem using Dynamic Programming:

For calculating the current row of the dp[] array we require only previous row, but if we start traversing the rows from right to left then it can be done with a single row only.

Below is the implementation of the above approach:

Java




// Java program for the above approach
 
import java.util.*;
 
class GFG {
    static int knapSack(int W, int wt[], int val[], int n)
    {
        // Making and initializing dp array
        int[] dp = new int[W + 1];
 
        for (int i = 1; i < n + 1; i++) {
            for (int w = W; w >= 0; w--) {
 
                if (wt[i - 1] <= w)
 
                    // Finding the maximum value
                    dp[w]
                        = Math.max(dp[w], dp[w - wt[i - 1]]
                                            + val[i - 1]);
            }
        }
        // Returning the maximum value of knapsack
        return dp[W];
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int profit[] = { 60, 100, 120 };
        int weight[] = { 10, 20, 30 };
        int W = 50;
        int n = profit.length;
        System.out.print(knapSack(W, weight, profit, n));
    }
}
 
// This code is contributed by gauravrajput1
 
 
Output
220 

Time Complexity: O(N * W). As redundant calculations of states are avoided
Auxiliary Space: O(W) As we are using a 1-D array instead of a 2-D array

Please refer complete article on Dynamic Programming | Set 10 ( 0-1 Knapsack Problem) for more details!



Next Article
Java Program for Min Cost Path
author
kartik
Improve
Article Tags :
  • Java Programs
  • knapsack

Similar Reads

  • Space Optimized DP Solution for 0-1 Knapsack Problem in Java
    In this article, we will learn about the space-optimized DP solution for the 0-1 Knapsack Problem in Java. Problem StatementA thief wants to rob a store at someplace. The thief is carrying a bag ( i.e. Knapsack ) of capacity W and the store has n number of total items, their weights, and values are
    3 min read
  • Java Program for Subset Sum Problem | DP-25
    Write a Java program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: se
    8 min read
  • Java Program for Min Cost Path
    Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (inc
    3 min read
  • Java Program For Chocolate Distribution Problem
    Given an array of n integers where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are m students, the task is to distribute chocolate packets such that: Each student gets one packet.The difference between the number of chocolat
    3 min read
  • Java Program for Minimum product subset of an array
    Given an array a, we have to find the minimum product possible with the subset of elements present in the array. The minimum product can be a single element also. Examples: Input : a[] = { -1, -1, -2, 4, 3 } Output : -24 Explanation : Minimum product will be ( -2 * -1 * -1 * 4 * 3 ) = -24 Input : a[
    3 min read
  • Java Program for Largest Sum Contiguous Subarray
    Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum. Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. Kadane's Algorithm: Initialize: max_so_far = INT_MIN max_ending_here = 0 Loop for
    5 min read
  • Java Program for Coin Change
    Write a Java program for a given integer array of coins[ ] of size N representing different types of denominations and an integer sum, the task is to count the number of coins required to make a given value sum. Examples: Input: sum = 4, coins[] = {1,2,3}, Output: 4Explanation: there are four soluti
    8 min read
  • Java Program for Number of pairs with maximum sum
    Write a java program for a given array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i < j.Example: Input : arr[] = {1, 1, 1, 2, 2, 2}Output: 3Explanation: The maximum possible pair sum where i<j is 4, which is given by 3 pairs, so the answer is 3 the pai
    4 min read
  • Java Program to Sort Items By Weight
    Given two array items and weights which denotes items and their respective weights. Both arrays are of equal length. For every index 'i', items[i] and weights[i] represent the ith item name and its weight respectively. Your task is to return a new array of items sorted in decreasing order by their w
    3 min read
  • Java Program to Minimize the Maximum Element of an Array
    Given two integers N and K. Create an array of N positive integers such that the sum of all elements of the array is divisible by K and the maximum element in the array is the minimum possible. You have to find the Maximum element of that array. Example: Input : N=5, K=11 Output : 3 Explanation : We
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences