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
27 changes: 27 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// 0-1 Knapsack problem
// Time complexity: O(weights.length * capacity)
// Space complexity: O(capacity) for dp array
public class Problem1 {
public int maxProfit(int[] profits, int[] weights, int capacity) {
int[] dp = new int[capacity + 1];
for (int row = 1; row < weights.length + 1; row ++) {
// Iterating backwards to avoid using modified dp value.
for (int col = capacity; col >= 1; col --) {
if (col >= weights[row - 1]) { // col is the max capacity
// Consider maximum between previous profit and sum of current weight's profit and maximum profit from the remaining weight.
dp[col] = Math.max(dp[col], profits[row - 1] + (dp[col - weights[row - 1]]));
}
}
}
return dp[capacity];
}
public static void main(String[] args) {
Problem1 ob = new Problem1();
int[] profits = new int[] {1, 2, 3};
int[] weights = new int[] {4, 5, 1};
int capacity = 4;
System.out.println(ob.maxProfit(profits, weights, capacity));
capacity = 5;
System.out.println(ob.maxProfit(profits, weights, capacity));
}
}
41 changes: 41 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

// Approach: HashMap
// Time: O(N)
// Space: O(N) for HashMap
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> indexMap = new HashMap<>();
for (int i = 0; i < nums.length; i ++) {
if (indexMap.containsKey(target - nums[i])) {
return new int[] {indexMap.get(target - nums[i]), i};
}
indexMap.put(nums[i], i);
}
throw new IllegalArgumentException("No solution");
}

public static void main(String[] args) {
Solution ob = new Solution();

int[] nums1 = {2,7,11,15};
System.out.println(Arrays.toString(ob.twoSum(nums1, 9))); // returns [0, 1]

int[] nums2 = {3,2,4};
System.out.println(Arrays.toString(ob.twoSum(nums2, 6))); // returns [1, 2]

int[] nums3 = {3,3};
System.out.println(Arrays.toString(ob.twoSum(nums3, 6))); // returns [0, 1]

int[] nums4 = {3};
System.out.println(Arrays.toString(ob.twoSum(nums4, 3))); // throws exception

int[] nums5 = {};
System.out.println(Arrays.toString(ob.twoSum(nums5, 0))); // throws exception

int[] nums6 = {2, 3};
System.out.println(Arrays.toString(ob.twoSum(nums6, 4))); // throws exception
}
}