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
34 changes: 34 additions & 0 deletions 0-1Knapsack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Time Complexity : O(m * n)
// Space Complexity : O(n)
// Any problem you faced while coding this : no

// Your code here along with comments explaining your approach
/*
This problem cant be solved in greedy,so while solving recursively, we see a lot of repetitive subproblems
to be solved.This can be done through DP. We take a DP array to respectively handle choose and no choose
cases of weights and match with capacity, thereby compute the max profit at every step
*/
class Solution {

public static int findMax(int[] weights, int[] profit, int totalCapacity) {
int m = weights.length;
int n = totalCapacity;

int[] dp = new int[n + 1];

for(int i = 0 ; i < m ; i++) {
for(int j = n ; j >= weights[i] ; j--) {
dp[j] = Math.max(dp[j], profit[i] + dp[j - weights[i]]);
}
}
return dp[n];
}

public static void main(String args[]) {
int[] items = {10, 20, 30, 40};
int[] profit = {130, 110, 170, 190};
int capacity = 50;

System.out.println(findMax(items, profit, capacity));
}
}
Empty file removed Problem1.java
Empty file.
Empty file removed Problem2.java
Empty file.
25 changes: 25 additions & 0 deletions TwoSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Time Complexity : O(n)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no


// Your code here along with comments explaining your approach
/*
I would take a map of integers and iterate the input array. During iteration, if complement/difference of
the target and incoming array element value already exists in the map, it means, we already recorded the
associated value to make the sum inside the map.So,we fetch and return that value(index) and
index of i. If not, record the first occurence of that nums[i] and its index.
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> sumMap = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++) {
int diff = target - nums[i];
if(sumMap.containsKey(diff))
return new int[]{i,sumMap.get(diff)};
sumMap.put(nums[i], i);
}
return new int[]{};
}
}