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
19 changes: 19 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//Use a HashMap to store each number’s value -> index as you scan.
// For each nums[i], compute complement = target - nums[i]; if it’s already in the map, return the stored index and i.
// O(n) time with O(n) extra space.

class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();

for (int i = 0; i < nums.length; i++) {
int cmp = target - nums[i];
if (map.containsKey(cmp)) {
return new int[]{map.get(cmp),i};
}
map.put(nums[i], i);
}

return new int[]{};
}
}
30 changes: 30 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// 0-1 Knapsack via bottom-up DP: dp[i][j] = max value using first i items within capacity j.
// For each item i and capacity j: if wt[i-1] > j -> can't take -> carry dp[i-1][j];
// else choose max of skipping (dp[i-1][j]) vs taking once (profit[i-1] + dp[i-1][j - wt[i-1]]).
// Time O(m*n)
// Space O(m*n)

class Solution {

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

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

}
}