Functions and Fractals - Recursive Trees - Bash!

  • + 0 comments
    import java.util.*;
    
    public class UnboundedKnapsack {
    
        public static int unboundedKnapsack(int k, int[] arr) {
            int[] dp = new int[k + 1];
            
            for (int i = 0; i <= k; i++) {
                for (int num : arr) {
                    if (i - num >= 0) {
                        dp[i] = Math.max(dp[i], dp[i - num] + num);
                    }
                }
            }
            
            return dp[k];
        }
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            
            int t = sc.nextInt();  // Number of test cases
            
            for (int test = 0; test < t; test++) {
                int n = sc.nextInt();  // Length of array
                int k = sc.nextInt();  // Target sum
                
                int[] arr = new int[n];
                for (int i = 0; i < n; i++) {
                    arr[i] = sc.nextInt();
                }
                
                int result = unboundedKnapsack(k, arr);
                System.out.println(result);
            }
            
            sc.close();
        }
    }