(Hacker Rank) Knapsack - Solution

Link to the problem: https://www.hackerrank.com/challenges/unbounded-knapsack

The solution below used the concept of Knapsack, related to Dynamic Programming, to solve this problem.


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static int[][] matrix;
    public static int[] list;
    public static int expectedSum;
   
    public static int knapsack(int volume, int indexList) {
        if (volume < 0) {
            return -1000000000; // a big number bc I want to use the 'notUse', because if I use the 'use', it will reach a sum bigger than the expected number
        }   
        if (indexList < 0) {
            return 0;
        }
       
        if (matrix[volume][indexList] != -1) {
            return matrix[volume][indexList];
        }
       
        int use = knapsack(volume-list[indexList], indexList)+list[indexList];
        int notUse = knapsack(volume, indexList-1);
        matrix[volume][indexList] = Math.max(use, notUse);
        return matrix[volume][indexList];
    }
   
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int numTestCase = sc.nextInt();
        for (int i = 0; i < numTestCase; i++) {
            int lenghtList = sc.nextInt();
            expectedSum = sc.nextInt();
           
            list = new int[lenghtList];
            for (int j = 0; j < lenghtList; j++) {
                list[j] = sc.nextInt();
            }
           
            matrix = new int[expectedSum+1][lenghtList];
            for (int j = 0; j < expectedSum+1; j++) {
                for (int k = 0; k < lenghtList; k++) {
                    matrix[j][k] = -1;
                }
            }
            System.out.println(knapsack(expectedSum, lenghtList-1));
        }
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução