I would just run it twice.
In the first run, find a βclassicβ solution with a better weight of less than 1000.
In the second run, increase the maximum value of 1000 to the maximum possible value that is allowed based on the previous solution.
Do not worry about the fact that "it is twice as slow", multiplying complexity by a constant, does not change the complexity, which is important in the knapsack problem.
If your code works, you can probably consider a better solution like this
System.out.println(knapsack(wt,2*W - knapsack(wt, W));
Or you can write it like this to make it clearer what is happening (it does the same thing as one line above)
int bestClassicSolution = knapsack(wt, W); int differenceAgainstMaxWeight = W - bestClassicSolution; int newMaxWeight = W + differenceAgainstMaxWeight; int bestSolution = knapsack(wt, newMaxWeight); System.out.println(bestSolution);
EDIT: The solution above works for this condition. select as big solution as possible, but it must not differ from 1000 more than "below 1000" best solution . OP actually wants a little different - the "limit" remains, but it should be closest to 1000, but as high as possible.
Thus, a real solution could create a backpack method that finds a solution with a minimum BUT value that should be greater than the min variable.
public static void main(String[] args) throws Exception { BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); int [] wt=new int[5]; int W = 1000; System.out.println("Enter Weight 5 weights"); for(int i=0; i<5; i++) { wt[i]=Integer.parseInt(reader.readLine()); } int bestClassicSolution = knapsack(wt, W); int differenceAgainstMaxWeight = W - bestClassicSolution; int newMaxWeight = W + differenceAgainstMaxWeight; int bestMaxSolution = reversedKnapsack(wt, newMaxWeight, W); int differenceAgainstWeightAboveW = W - bestMaxSolution; if (differenceAgainstWeightAboveW <= differenceAgainstMaxWeight){ System.out.println(bestMaxSolution); } else { System.out.println(bestClassicSolution); } } public static int reversedKnapsack(int wt[], int W, int min) {