📖 Scenario: Imagine you are organizing a small event and need to select activities to fill a fixed time slot. Each activity has a duration and a fun score. You want to maximize the total fun score without exceeding the total available time.This project will help you understand when to use a simple greedy approach and when to use dynamic programming (DP) to solve such problems.
🎯 Goal: You will create a list of activities, set a total available time, first try a greedy approach to select activities, then implement a dynamic programming solution to find the best combination. Finally, you will compare the results.
📋 What You'll Learn
Create a list of activities with exact durations and fun scores
Set a total available time variable
Implement a greedy selection based on highest fun per time ratio
Implement a dynamic programming solution to find the maximum fun score within time
Print the results of both approaches
💡 Why This Matters
🌍 Real World
This project models real-life scheduling and resource allocation problems where you must choose the best combination of tasks within limited time or resources.
💼 Career
Understanding when to use greedy algorithms versus dynamic programming is crucial for software engineers solving optimization problems efficiently.
Progress0 / 4 steps
1
Create the list of activities
Create a variable called activities as an array of objects with these exact entries: {name: 'A', duration: 3, fun: 5}, {name: 'B', duration: 2, fun: 3}, {name: 'C', duration: 4, fun: 7}, {name: 'D', duration: 1, fun: 2}
DSA Javascript
Hint
Use an array with objects. Each object has name, duration, and fun properties.
2
Set the total available time
Create a variable called totalTime and set it to 5
DSA Javascript
Hint
Just create a number variable named totalTime and assign 5.
3
Implement the greedy selection
Create a function called greedySelection that takes activities and totalTime. Inside, sort activities by descending fun/duration ratio, then select activities in order while total duration does not exceed totalTime. Return an array of selected activity names called greedyResult.
DSA Javascript
Hint
Sort by fun/duration ratio descending. Pick activities while total duration is within limit. Return selected names.
4
Implement dynamic programming and print results
Create a function called dpSelection that takes activities and totalTime. Use dynamic programming to find the maximum total fun score without exceeding totalTime. Return an object with maxFun and an array selected of activity names. Then print the results exactly as: console.log('Greedy selection:', greedyResult); and console.log('DP selection:', dpResult.selected, 'with total fun:', dpResult.maxFun);
DSA Javascript
Hint
Use a 2D array for DP table. Track max fun for each activity and time. Backtrack to find selected activities. Print results exactly as instructed.
Practice
(1/5)
1. Which of the following best describes when to use a greedy algorithm instead of dynamic programming?
easy
A. When the problem needs to store results of subproblems
B. When the problem requires checking all possible solutions
C. When overlapping subproblems are present
D. When the problem has the greedy choice property and optimal substructure
Solution
Step 1: Understand greedy choice property
A greedy algorithm works when choosing the best option at each step leads to a global optimum, known as the greedy choice property.
Step 2: Compare with dynamic programming conditions
Dynamic programming is used when problems have overlapping subproblems and optimal substructure, but greedy algorithms require only the greedy choice property and optimal substructure.
Final Answer:
When the problem has the greedy choice property and optimal substructure -> Option D
Quick Check:
Greedy choice property = Use greedy [OK]
Hint: Use greedy if local best leads to global best [OK]
Common Mistakes:
Confusing overlapping subproblems as greedy condition
Using dynamic programming when greedy suffices
Ignoring greedy choice property
2. Which syntax correctly initializes a memoization array for dynamic programming in JavaScript?
easy
A. const memo = new Array(n).fill(-1);
B. const memo = Array(n).map(() => 0);
C. const memo = new Array(n).map(() => 0);
D. const memo = Array.fill(n, -1);
Solution
Step 1: Understand Array initialization
Using new Array(n).fill(-1) creates an array of length n filled with -1, suitable for memoization since -1 indicates uncomputed.
Step 2: Check other options
A and C fill with 0, which conflicts if 0 is a valid result; map is also unnecessary. D is invalid syntax.
Final Answer:
const memo = new Array(n).fill(-1); -> Option A
Quick Check:
Use new Array(n).fill(value) for memo [OK]
Hint: Use new Array(n).fill(value) to initialize arrays [OK]
Common Mistakes:
Using map on uninitialized array
Wrong order of fill arguments
Using Array.fill which is invalid
3. What is the output of the following JavaScript code?
function maxSum(arr) {
let incl = arr[0];
let excl = 0;
for (let i = 1; i < arr.length; i++) {
let new_excl = Math.max(incl, excl);
incl = excl + arr[i];
excl = new_excl;
}
return Math.max(incl, excl);
}
console.log(maxSum([3, 2, 7, 10]));