Christmas Dinner Ingredient Optimization
0:00:00
You’re a data scientist working for a smart grocery platform that helps families automatically plan their Christmas dinner based on their dietary preferences and pantry availability.
Each Christmas recipe consists of several ingredients, and each ingredient has different brands with different prices. Families want the cheapest possible ingredient combination but only using brands they have marked as acceptable and only those ingredients they do not already have in their pantry.
Write a SQL query to determine the cheapest valid shopping cost for each recipe for family_id = 1, while also identifying whether the recipe is feasible to make.
For each recipe, compute:
missing_ingredients: number of ingredients the family does not already have in their pantrymin_total_cost: total minimum cost required to buy missing ingredients- feasible:
'Yes'if every missing ingredient has at least one acceptable brand available'No'otherwise (andmin_total_costshould beNULL)
Note: Sort results by missing_ingredients ASC and min_total_cost ASC (NULLS LAST)
Schema
Input
recipes Table
| Column | Type |
|---|---|
| recipe_id | INTEGER |
| ingredient_id | INTEGER |
ingredient_brands Table
| Column | Type |
|---|---|
| ingredient_id | INTEGER |
| brand_id | INTEGER |
| price | DECIMAL |
pantry Table
| Column | Type |
|---|---|
| family_id | INTEGER |
| ingredient_id | INTEGER |
acceptable_brands Table
| Column | Type |
|---|---|
| family_id | INTEGER |
| brand_id | INTEGER |
Output
| Column | Type |
|---|---|
| recipe_id | INTEGER |
| missing_ingredients | INTEGER |
| min_total_cost | DECIMAL |
| feasible | VARCHAR |
Example
Input
recipes Table
| recipe_id | ingredient_id |
|---|---|
| 1 | 100 |
| 1 | 200 |
| 1 | 300 |
| 2 | 200 |
| 2 | 400 |
pantry Table
| family_id | ingredient_id |
|---|---|
| 1 | 100 |
ingredient_brands Table
| ingredient_id | brand_id | price |
|---|---|---|
| 200 | 10 | 3.50 |
| 200 | 11 | 2.99 |
| 300 | 20 | 8.50 |
| 400 | 30 | 6.75 |
acceptable_brands Table
| family_id | brand_id |
|---|---|
| 1 | 10 |
| 1 | 20 |
| 1 | 30 |
Output
| recipe_id | missing_ingredients | min_total_cost | feasible |
|---|---|---|---|
| 1 | 2 | 12.00 | Yes |
| 2 | 2 | 10.25 | Yes |
Explanation
For Recipe 1, the required ingredients are 100, 200, and 300. The pantry already contains ingredient 100, so only 200 and 300 are missing. The cheapest acceptable option for ingredient 200 is brand 10 at $3.50, since brand 11 is not allowed. For ingredient 300, the cheapest acceptable option is brand 20 at $8.50. This makes the total cost $12.00, and the recipe is feasible.
For Recipe 2, the required ingredients are 200 and 400. The cheapest acceptable choice for ingredient 200 is again $3.50, and for ingredient 400 it is $6.75. The total comes to $10.25, and this recipe is also feasible.
.
.
.
.
Comments