Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort jobs by their profit in descending order.
DSA C++
bool compare(Job a, Job b) {
return a.profit [1] b.profit;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' will sort in ascending order, which is incorrect for maximizing profit.
Using '==' or '!=' does not define an order.
✗ Incorrect
We want to sort jobs so that the job with higher profit comes first, so we use '>' operator.
2fill in blank
mediumComplete the code to find the maximum deadline among all jobs.
DSA C++
int maxDeadline = 0; for (int i = 0; i < n; i++) { if (jobs[i].deadline [1] maxDeadline) { maxDeadline = jobs[i].deadline; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' will find the minimum deadline, which is incorrect.
Using '<=' or '>=' may cause unnecessary updates.
✗ Incorrect
We update maxDeadline only if the current job's deadline is greater than maxDeadline.
3fill in blank
hardFix the error in the code to mark the slot as occupied after scheduling a job.
DSA C++
for (int j = jobs[i].deadline; j > 0; j--) { if (slot[j] == false) { slot[j] = [1]; result[j] = i; break; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning false will mark the slot as free, which is wrong.
Assigning 1 or 0 may cause type mismatch.
✗ Incorrect
We mark the slot as true to indicate it is occupied.
4fill in blank
hardFill both blanks to initialize the slot array and result array correctly.
DSA C++
bool slot[[1] + 1]; int result[[2] + 1]; for (int i = 0; i <= maxDeadline; i++) { slot[i] = false; result[i] = -1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using n (number of jobs) may cause incorrect array size.
Using maxProfit or deadline variable names that are undefined.
✗ Incorrect
Both arrays should be sized based on maxDeadline to cover all possible slots.
5fill in blank
hardFill all three blanks to print the scheduled jobs and total profit.
DSA C++
int totalProfit = 0; for (int i = 1; i <= maxDeadline; i++) { if (result[i] != -1) { cout << jobs[[1]].id << " "; totalProfit += jobs[[2]].profit; } } cout << "\nTotal Profit: " << [3] << endl;
Attempts:
3 left
💡 Hint
Common Mistakes
Using i as index for jobs is wrong because i is slot number, not job index.
Printing jobs[i] directly is incorrect as jobs is an array of objects.
Printing totalProfit before calculation.
✗ Incorrect
We use result[i] to get the job index for printing and profit addition. totalProfit is printed at the end.
