Tree-Dependent Knapsack
Updated
Problem statement
You are given n items arranged as one rooted dependency tree. Item i has cost cost[i], value value[i], and parent parent[i]. The root has parent -1.
You may select any set of items whose total cost is at most capacity. Selecting a non-root item requires selecting its parent, which also recursively requires every ancestor through the root.
Return the maximum total value of a valid selected set. Selecting no items is allowed.
Function
maximizeDependentValue(parent: int[], cost: int[], value: int[], capacity: int) → intExamples
Example 1
parent = [-1,0,0,1]cost = [2,2,3,2]value = [3,4,5,6]capacity = 6return = 13Select items 0, 1, and 3. Their total cost is 6, their value is 13, and every selected item's parent is present.
Example 2
parent = [-1,0,0]cost = [5,1,1]value = [2,100,100]capacity = 2return = 0The root does not fit, so neither child can be selected.
Example 3
parent = [-1,0,0,2]cost = [1,3,2,2]value = [1,8,4,10]capacity = 5return = 15Select the root, item 2, and item 3 for total cost 5 and value 15.
Constraints
1 <= n == parent.length == cost.length == value.length <= 200.- Exactly one index has parent
-1; all other parent indices define one rooted tree. 0 <= cost[i] <= capacity <= 2000.0 <= value[i] <= 10^6.- The answer fits in a signed 32-bit integer.
More Google Phone Screen questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Periodic-Color Binary Forest RootsPHONE SCREEN · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Best Stock Trade with Buy and Sell DaysPHONE SCREEN · Seen Nov 2026
- Word Chain Jumps in a GridPHONE SCREEN · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
- Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
- Course Schedule Cycle DetectionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Recursive Display SortFigma · PHONE SCREEN · ONSITE INTERVIEWFigma interview questions
- Lowest Common Manager for Employee GroupsAmazon · PHONE SCREEN
- Longest Increasing Path in a MatrixNew Relic · PHONE SCREEN · ONSITE INTERVIEW
- File Encryption Tree OptimizationDatabricks · PHONE SCREEN · ONSITE INTERVIEWDatabricks interview questions
- Subtree Access OverridesPinterest · PHONE SCREENPinterest interview questions
- Maximum Path Sum Between Marked NodesDoorDash · PHONE SCREENDoorDash interview questions
- House Robber IIIOkta · PHONE SCREENOkta interview questions
- House Robber IIIGoldman Sachs · PHONE SCREENGoldman Sachs interview questions
- House Robber IIIVisa · PHONE SCREENVisa interview questions
- Predicate Expression Tree EvaluatorMongoDB · PHONE SCREENMongoDB interview questions