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
31 changes: 31 additions & 0 deletions KnapSack.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// In this problem, we use a dynamic programming approach to solve the 0/1 Knapsack problem. We create a 2D array to store the maximum value that can be obtained with a given weight capacity and number of items.
// We iterate through each item and weight capacity, deciding whether to include the current item or not based on which choice yields a higher value.
//Time Complexity: O(n*W) where n is the number of items and W is the maximum weight capacity of the knapsack.
//Space Complexity: O(n*W) for the 2D array used to store the maximum values.

class Solution {
fun knapsack(W: Int, valArr: IntArray, wt: IntArray): Int {
val n = wt.size
val dp = Array(n + 1) { IntArray(W + 1) }

// Build table dp[][] in bottom-up manner
for (i in 0..n) {
for (j in 0..W) {
if (i == 0 || j == 0) {
dp[i][j] = 0
} else {
var pick = 0
// Pick i-th item if it does not exceed the capacity of knapsack
if (wt[i - 1] <= j) {
pick = valArr[i - 1] + dp[i - 1][j - wt[i - 1]]
}
// Don't pick the i-th item
val notPick = dp[i - 1][j]

dp[i][j] = maxOf(pick, notPick)
}
}
}
return dp[n][W]
}
}
22 changes: 22 additions & 0 deletions TwoSum.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// In this problem, we have kept a hash map to store the numbers we have seen so far along with their indices.
// if we find a number such that the difference between the target and the current number exists in the map, we return the indices of these two numbers.
//Time Complexity: O(n) where n is the number of elements in the input array.
//Space Complexity: O(n) for the hash map storing the elements.

class Solution {
fun twoSum(nums: IntArray, target: Int): IntArray {
val map = HashMap<Int, Int>()
for ((index,num) in nums.withIndex()) {
val toCheck = target - num
if (map.contains(toCheck))
{
return intArrayOf(map[toCheck]!!, index)
}
else {
map.put(num, index)
}
}

return intArrayOf(0,0)
}
}