0
0
DSA Cprogramming~30 mins

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

Choose your learning style9 modes available
DP vs Recursion vs Greedy Choosing the Right Tool
📖 Scenario: Imagine you are helping a small delivery company decide the best way to pack their trucks with packages. Each package has a weight and a value. The company wants to maximize the total value of packages in the truck without exceeding the weight limit.There are three ways to solve this problem: simple recursion, dynamic programming, and a greedy approach. You will learn how to set up the data, configure the problem, apply each method, and see the results.
🎯 Goal: Build a program that uses recursion, dynamic programming, and greedy methods to solve the package packing problem. You will compare their outputs to understand which method works best for this problem.
📋 What You'll Learn
Create an array of package weights and values
Set a maximum weight limit for the truck
Implement a recursive function to find max value
Implement a dynamic programming solution for max value
Implement a greedy approach based on value-to-weight ratio
Print the results of all three methods
💡 Why This Matters
🌍 Real World
Delivery companies and logistics use these methods to pack trucks efficiently, saving fuel and time.
💼 Career
Understanding these approaches helps in roles like software engineering, data analysis, and operations research where optimization problems are common.
Progress0 / 4 steps
1
Create package data arrays
Create two arrays called weights and values with these exact values: weights = {2, 3, 4, 5} and values = {3, 4, 5, 6}. Also create an integer n set to 4 representing the number of packages.
DSA C
Hint

Use array syntax to create weights and values. Set n to 4.

2
Set the maximum weight limit
Create an integer variable called maxWeight and set it to 5 to represent the truck's weight limit.
DSA C
Hint

Declare int maxWeight = 5; inside main.

3
Implement recursive solution
Write a recursive function called knapsackRecursive that takes three parameters: int i (current index), int w (current weight), and returns the maximum value that can be obtained without exceeding maxWeight. Use the arrays weights and values and the variable n. Then call this function from main with i = 0 and w = 0 and store the result in int resultRec.
DSA C
Hint

Use recursion to try including or excluding the current package. Return the max value.

4
Print the recursive result
Add a printf statement in main to print the text "Recursive result: " followed by the value of resultRec.
DSA C
Hint

Use printf("Recursive result: %d\n", resultRec); to print.