0/1 Knapsack
Updated
Problem statement
You have a backpack with a weight limit and a list of items. Return the largest total value you can carry without exceeding the limit.
For this exercise, assume item i has integer weight weights[i] and integer value values[i]. Each item is available once. You may choose no items, and unused capacity is allowed. Items with equal weights or values are still separate items.
The arrays describe the same items in the same order. The backpack limit is capacity.
Function
maxBackpackValue(weights: int[], values: int[], capacity: int) → intExamples
Example 1
weights = [2,3,4]values = [4,5,7]capacity = 5return = 9Take the items of weights 2 and 3. Their total weight is 5 and their total value is 4 + 5 = 9. Taking the weight-4 item alone gives value 7, so 9 is best.
Example 2
weights = [3,5]values = [8,12]capacity = 2return = 0Neither item fits. Choosing no items gives value 0.
Constraints
0 <= weights.length <= 200values.length == weights.length1 <= weights[i] <= 100000 <= values[i] <= 100000 <= capacity <= 10000
More JP Morgan Chase Online Assessment questions
- Find Total CostOA · Seen Oct 2026
- Minimum Meeting RoomsOA · Seen Oct 2026
- Count Dropped RequestsOA · Seen Oct 2026
- Maximize Minimum Deployment DifficultyOA · Seen Oct 2026
- Task SchedulingOA · Seen Oct 2026
- Substring RemovalOA · Seen Oct 2026
- Maximum Game Board ScoreOA · Seen Sep 2026
- Minimum Digit Changes Between String HalvesOA · Seen Sep 2026
- Same Substring Within BudgetOA · Seen Sep 2026
- Invert Ad Visibility BitsOA · Seen Aug 2026
Similar questions at other companies
- 0/1 KnapsackConfluent · OAConfluent interview questions
- Maximum Equal-Bit Pairs in a SubsequenceAmazon · OA
- Minimum Cost to Tile a Strip with Widths 1, 2, and 3Infosys · OAInfosys interview questions
- Frog Paths Without Long RunsSusquehanna International Group (SIG) · OASusquehanna International Group (SIG) interview questions
- Maximum Escape Game ScoreMicrosoft · OAMicrosoft interview questions
- Cities on Shortest Delivery RoutesMathWorks · OAMathWorks interview questions
- Count Lucky TicketsThe D.E. Shaw Group · OAThe D.E. Shaw Group interview questions
- Longest Subsequence That Is a SubstringBooking.com · OA
- Count Routes Through Four Shop TypesOpenAI · OAOpenAI interview questions
- Maximum Subarray SumStraive · OA
Interview reports that mention this question
JP Morgan Chase interview experiences
- JPMorgan Quant Stats Superdays: 3 Experiences (Part 3 of 3)
- JPMorgan Quant Modeling Superdays: 7 Experiences (Part 2 of 3)
- JPMorgan Quant Intern Superday: 19 Experiences (Part 1 of 3)
- JP Morgan Chase Data and AI Intern Superday: 11 Experiences
- JPMorgan Code for Good India 2024: 6 Experiences (Part 5 of 5)