Java Challenge - The Knapsack Problem

This community-built FAQ covers the “The Knapsack Problem” code challenge in Java. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Java challenge The Knapsack Problem

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

private static int getArray(int array, int exceptIndex) {
int newArray = new int[array.length - 1];
for (int i = 0; i < array.length; i++) {
if (i < exceptIndex) {
newArray[i] = array[i];
} else if (i > exceptIndex) {
newArray[i - 1] = array[i];
}
}
return newArray;
}

private static int knapsack(int weightCap, int weights, int values, HashMap<Integer, Integer> record) {
if (weightCap == 0) {
return 0;
}
if (record.containsKey(weightCap)) {
return record.get(weightCap);
}
int largestSum = 0;
for (int i = 0; i < weights.length; i++) {
int weight = weights[i];
int newWeightCap = weightCap - weight;
if (newWeightCap < 0) {
continue;
}
int value = values[i];
int sum = value + knapsack(newWeightCap, getArray(weights, i), getArray(values, i));
if (largestSum < sum) {
largestSum = sum;
}
}
record.put(weightCap, largestSum);
return largestSum;
}

public static int knapsack(int weightCap, int weights, int values) {
return knapsack(weightCap, weights, values, new HashMap<Integer, Integer>());
}

public class Knapsack {
  public static void main(String[] args) {
    int values[] = new int[] {50, 60, 100};
    int weights[] = new int[] {3, 6, 8};
    int weightCap = 10;
    System.out.println(knapsack(weightCap, weights, values));
  }
 
  public static int knapsack(int weightCap, int weights[], int values[]) {
    return knapsackHelper(weightCap, weights, values, 0);
  }
  
  // Start from the beginning of the item's and for each item lets try to fit the current item in our bag
 // and then skipping the current item, and taking the condition that has the greatest value.
  public static int knapsackHelper(int weightCap, int weights[], int values[], int index) {
    // If we reached the end of all the items, return 0.
    if (index >= weights.length) {
      return 0;
    }
    // Value for taking the current item we are on.
    int takeItem = 0;
   // Value if we skip the current item.
    int skipItem = 0;
 
    // If we can fit the current item in our bag, lets try taking it and subtracting it's weight from out cap.
    if (weights[index] <= weightCap) {
      takeItem = knapsackHelper(weightCap - weights[index], weights, values, index + 1) + values[index];
    }

    // Let's see what values we can get if we skip this current item.
    skipItem = knapsackHelper(weightCap, weights, values, index + 1);
    
   // Return the condition with the greater value.
    return Math.max(takeItem, skipItem);
  }
}

import java.util.Arrays;

public class Knapsack{

public static void main(String[] args) {
	// TODO Auto-generated method stub
	int values[] = new int[]{50, 60, 100};
	int weights[] = new int[]{3, 6, 8};
	int weightCap = 10;

	// exemples to test the code :
	// int values[] = new int[]{15, 30, 150, 30, 5, 15, 30};
	// int weights[] = new int[]{2, 6, 1, 10, 1, 3, 4};
	// int values[] = new int[]{15, 30, 150, 30};
	// int weights[] = new int[]{2, 6, 1, 10};
	// int values[] = new int[]{100, 100, 100, 100};
	// int weights[] = new int[]{1, 10, 6, 2};
	// int values[] = new int[]{15, 30, 150, 30};
	// int weights[] = new int[]{2, 2, 2, 2};
	// int values[] = new int[]{150, 150, 150, 150};
	// int weights[] = new int[]{2, 6, 1, 10};

	// See the arrays before classifying them
	System.out.println(Arrays.toString(weights));
	System.out.println(Arrays.toString(values));
	System.out.println("------------");
	System.out.println(knapsack(weightCap, weights, values));

}

public static int knapsack(int weightCap, int weights[], int values[]) {
	int valueBegin = 0;
	int weightBegin = 0;
	int valueEnd = 0;
	int weightEnd = 0;
	// Classify the array of values from largest to smallest and match the array of weights
	classifyValuesAndWeights(weights, values);
	System.out.println(Arrays.toString(weights));
	System.out.println(Arrays.toString(values));
	System.out.println("------------");
	// We take the biggest possible value of take starting from the begin
	for (int i = 0; i < weights.length; i++) {
		if (weightBegin <= weightCap
				&& weightBegin + weights[i] <= weightCap) {
			weightBegin += weights[i];
			valueEnd += values[i];
		}
	}
	// We take the biggest possible value of take starting from the end
	for (int i = weights.length - 1; i >= 0; i--) {
		if (weightEnd <= weightCap && weightEnd + weights[i] <= weightCap) {
			weightEnd += weights[i];
			valueEnd += values[i];
		}
	}
	// We compare the values between valueBegin and valueEnd
	if (valueEnd > valueBegin) {
		return valueEnd;
	} else {
		return valueBegin;
	}
}

// Classify the array of values from largest to smallest and match the array of weights
public static int[] classifyValuesAndWeights(int weights[], int values[]) {
	int x, y;
	for (int i = 0; i < weights.length - 1; i++) {
		for (int j = 0; j < weights.length - 1; j++) {
			if (values[j] < values[j + 1]) {
				y = values[j + 1];
				values[j + 1] = values[j];
				values[j] = y;
				x = weights[j + 1];
				weights[j + 1] = weights[j];
				weights[j] = x;
			}
		}
	}
	return weights;
}

}