Prepin
Log in

You have a knapsack with a maximum capacity of C, and there are n items available, each with a weight of w[i] and a value of v[i]. The goal is to maximize the total value in the knapsack without surpassing its maximum capacity.

Approach / Explanation

This question prompts you to tackle a well-known issue in computer science referred to as the Knapsack problem. The goal is to determine the best combination of items, each with its own value and weight, in order to maximize the total value of the items in your knapsack while staying within the weight capacity (C). When addressing the Knapsack Problem, keep these important points in mind: It is a combinatorial optimization challenge where the aim is to identify the best solution from a vast array of potential solutions. It is classified as a 0/1 problem, meaning that items cannot be partially included or duplicated; you must either select the entire item or leave it out completely. To solve this problem efficiently, you will probably need to employ dynamic programming techniques.

Suggested Answer

Below is a method to address the problem using the Python programming language, specifically employing dynamic programming: def knapSack ( C , w , v , n ) : if n == 0 or C == 0 : return 0 if ( w [ n - 1 ] > C ) : return knapSack ( C , w , v , n - 1 ) else : return max ( v [ n - 1 ] + knapSack ( C - w [ n - 1 ] , w , v , n - 1 ) , knapSack ( C , w , v , n - 1 ) ) This example shows that the knapSack function checks each item to determine if it can be included in the knapsack. If the weight of an item exceeds the total capacity (C), that item is disregarded. If it can be included, the function computes the maximum value of that item along with the knapsack's remaining capacity, ultimately returning the highest of these values.

Alternative Answer

Here is another Python example that is somewhat more efficient due to its use of dynamic programming: def knapSack ( C , w , v , n ) : K = [ [ 0 for w in range ( C + 1 ) ] for i in range ( n + 1 ) ] for i in range ( n + 1 ) : for wt in range ( C + 1 ) : if i == 0 or wt == 0 : K [ i ] [ wt ] = 0 elif w [ i - 1 ] <= wt : K [ i ] [ wt ] = max ( v [ i - 1 ] + K [ i - 1 ] [ wt - w [ i - 1 ] ] , K [ i - 1 ] [ wt ] ) else : K [ i ] [ wt ] = K [ i - 1 ] [ wt ] return K [ n ] [ C ] In this code snippet, a 2-D matrix K[][] is constructed using a bottom-up approach. For each weight from 0 to C, the maximum value that can fit into the knapsack is saved in the matrix. The ultimate answer will be found in K[n][C]. This approach eliminates the need for recalculating and redoing subproblems, enhancing overall efficiency.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Uber

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.