Created
May 2, 2017 06:27
-
-
Save GarimaDamani/2041b895a6c5ba24cefccb34d730af60 to your computer and use it in GitHub Desktop.
@hackerrank: Algorithm: Dynamic Programming: Knapsack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Knapsack { | |
public static void main(String[] args) { | |
Scanner input = new Scanner(System.in); | |
int noOfInputs = input.nextInt(); | |
for (int x = 0; x < noOfInputs; x++) { | |
int noOfelements = input.nextInt(); | |
int capacity = input.nextInt(); | |
int[] elements = new int[noOfelements]; | |
int[][] table = new int[capacity + 1][noOfelements]; | |
for (int j = 0; j < noOfelements; ++j) { | |
elements[j] = input.nextInt(); | |
table[0][j] = 0; | |
} | |
for (int y = 1; y <= capacity; ++y) { | |
for (int z = 0; z < noOfelements; ++z) { | |
if (z == 0) { | |
if (y >= elements[z]) { | |
table[y][z] = table[y - elements[z]][z] + elements[z]; | |
} else { | |
table[y][z] = 0; | |
} | |
} else { | |
if (y >= elements[z]) { | |
table[y][z] = Math.max(table[y][z - 1], table[y - elements[z]][z] + elements[z]); | |
} else { | |
table[y][z] = table[y][z - 1]; | |
} | |
} | |
} | |
} | |
System.out.println(table[capacity][noOfelements - 1]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment