Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Knapsack01.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Idea is to use pick and no pick elements to fill the knapsack
// Use bottom up - DP array to store sub problem results and use them to solve larger problems
// Time Complexity: O(n)
// Space Complexity: O(n)
public class Knapsack01{

public int knapsack(int W, int[] val, int[] wt,int index) {
int n = wt.length;
int[][] dp = new int[n + 1][W + 1];

for (int i = 0; i <= n; i++) {
for (int j = 0; j <= W; j++) {
// If there is no item or the knapsack's capacity is 0
if (i == 0 || j == 0)
dp[i][j] = 0;
else {
int pick = 0;
// Pick ith item if it does not exceed the capacity of knapsack
if (wt[i - 1] <= j)
pick = val[i - 1] + dp[i - 1][j - wt[i - 1]];
int notPick = dp[i - 1][j];
dp[i][j] = Math.max(pick, notPick);
}
}
}
return dp[n][W];
}
}
Empty file removed Problem1.java
Empty file.
Empty file removed Problem2.java
Empty file.
24 changes: 24 additions & 0 deletions TwoSumProblem.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import java.util.HashMap;

//Idea is to use Hashmap to store the value and index.
//While inserting into the hashmap we simultaneously check for the compliment value (target-current value)
// Time Complexity: O(n)
// Space Complexity: O(n)
public class TwoSumProblem{

public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++)
{
if(hm.containsKey(target-nums[i]))
{
return new int[]{i,hm.get(target-nums[i])};
}
else
{
hm.put(nums[i], i);
}
}
return new int[]{-1,-1};
}
}