HTML & JS
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
//package algoconcept;

import java.util.Scanner;

/**
 *
 * @author Hemant Dhanuka
 */
 class KnapsackProblemByMe {

    static int weight[];//={1,3,4,5};
    static int value[];//={1,4,5,7};
    //static int representaion[]={0,0,0,0};
    static int dataStorage[];
    static int maxweight;

    static void myRecursion(int temp[], int i) {
        int totalweigt = 0;
        int totalValue = 0;
        for (int p = 0; p < temp.length; p++) {
            if (temp[p] == 1) {
                totalweigt += weight[p];
                totalValue += value[p];
            }
        }

        if (dataStorage[totalweigt] < totalValue) {
            dataStorage[totalweigt] = totalValue;
        }
        if (i >= temp.length) {
            return;
        }

        // if(i+1<temp.length){
        myRecursion(temp, i + 1);
        int temp1[] = new int[temp.length];
        for (int q = 0; q < temp.length; q++) {
            temp1[q] = temp[q];
        }

        temp1[i] = 1;
        myRecursion(temp1, i + 1);
        //}
    }

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        int totalCases = s.nextInt();
        for (int r = 0; r < totalCases; r++) {
            int N = s.nextInt();
            weight = new int[N];
            value = new int[N];
            int indvalueForThisWeight = s.nextInt();

            for (int i = 0; i < N; i++) {
                value[i] = s.nextInt();
            }
            for (int i = 0; i < N; i++) {
                weight[i] = s.nextInt();
            }

            maxweight = 0;
            for (int x : weight) {
                maxweight += x;
            }
            dataStorage = new int[maxweight + 1];
            myRecursion(new int[N], 0);
            System.out.println(findMaximumValueUnderGivenWeight(indvalueForThisWeight));
           
           //just to see values what weigts and values..
           // printWeightAndValue();

        }
    }

    static void printWeightAndValue() {
        int count = 0;
        for (int x : dataStorage) {

            System.out.println(count + "- " + x);
            count++;
        }
    }

    private static int findMaximumValueUnderGivenWeight(int indvalueForThisWeight) {
        int max = 0;
        if (indvalueForThisWeight > maxweight) {
            indvalueForThisWeight = maxweight;
        }
        for (int i = 1; i <= indvalueForThisWeight; i++) {
            if (dataStorage[i] > max) {
                max = dataStorage[i];
            }
        }
        return max;

    }

}

Generated URL:

Output:

3
Report Bug