0
0
DSA Typescriptprogramming~30 mins

DP vs Recursion vs Greedy Choosing the Right Tool in DSA Typescript - Build Both Approaches

Choose your learning style9 modes available
DP vs Recursion vs Greedy: Choosing the Right Tool
📖 Scenario: Imagine you are helping a delivery company decide the best way to pack boxes with items to maximize value without exceeding weight limits. You will explore three ways to solve this: simple recursion, greedy choice, and dynamic programming.
🎯 Goal: You will create a list of items with weights and values, set a maximum weight limit, then write code to find the best total value using recursion, greedy, and dynamic programming approaches. Finally, you will print the results to compare.
📋 What You'll Learn
Create a list of items with exact weights and values
Set a maximum weight limit variable
Write a recursive function to find max value without exceeding weight
Write a greedy function that picks items by value-to-weight ratio
Write a dynamic programming function to find max value efficiently
Print the results of all three methods
💡 Why This Matters
🌍 Real World
Packing delivery boxes or loading cargo efficiently to maximize value without exceeding weight limits.
💼 Career
Understanding when to use recursion, greedy algorithms, or dynamic programming is key for software engineers solving optimization problems.
Progress0 / 4 steps
1
Create the list of items
Create a variable called items as an array of objects with these exact entries: { weight: 2, value: 3 }, { weight: 3, value: 4 }, { weight: 4, value: 5 }, and { weight: 5, value: 8 }.
DSA Typescript
Hint

Use const items = [ ... ] with objects inside.

2
Set the maximum weight limit
Create a variable called maxWeight and set it to 8.
DSA Typescript
Hint

Use const maxWeight = 8; to set the limit.

3
Write the recursive function to find max value
Write a function called knapsackRecursive that takes index and remainingWeight as parameters and returns the maximum value. Use recursion to decide whether to include or exclude the current item at items[index]. If index is out of range or remainingWeight is zero or less, return 0.
DSA Typescript
Hint

Use recursion with base case when index is beyond last item or no weight left.

4
Print the results of all methods
Write three lines to print the results of calling knapsackRecursive(0, maxWeight), knapsackGreedy(), and knapsackDP(). Use console.log with labels: "Recursive:", "Greedy:", and "DP:" respectively.
DSA Typescript
Hint

Use console.log("Recursive:", knapsackRecursive(0, maxWeight)) and similar for greedy and DP.