Colorful Knapsack

You are given 'N' stones labeled from 1 to 'N'. The 'i-th' stone has the weight W[i]. There are 'M' colors labeled by integers from 1 to 'M'. The 'i-th' stone has the color C[i] which is an integer between 1 to 'M', both inclusive.

You have been required to fill a Knapsack with these stones. The Knapsack can hold a total weight of 'X'.

You are required to select exactly 'M' stones; one of each color. The sum of the weights of the stones must not exceed 'X'. Since you paid a premium for a Knapsack with capacity 'X', you are required to fill the Knapsack as much as possible.

Write a program to calculate the best way to fill the Knapsack - that is, the unused capacity should be minimized.

Input format:
The first line contains three integers 'N', 'M', and 'X', separated by a single space. Where 'N' represents the total number of stones, 'M' represents the total number of colour stones, and 'X' represents the total weight of the knapsack.

The second line contains 'N' integers, W[1], W[2], W[3] ..W[i]… W[N], separated by a single space. 

The third line contains 'N' integers C[1], C[2], C[3] ..C[i]… C[N], separated by single space.
Output Format:
The output prints the minimum unused capacity of the Knapsack(a single integer). If there is no way to fill the Knapsack, print -1.
Constraints :
1 <= M <= N <= 100
1 <= X <= 10000
1 <= W[i] <= 100
1 <= C[i] <= M

Time Limit: 1 sec
CodingNinjas
author
2y
Recursive Approach
  1. Create an array/list of size m+1. Let’s call this as weights, and add each weight of i’th color at the index i.
  2. Call a recursive function with color 1 and having current weight as 0. ...read more
CodingNinjas
author
2y
Memoization
  1. Create an array of the vector of size m+1 let’s call it ‘weights’, and add each weight of i’th color at the index i.
  2. Create a 2D integer array of size (M+1)*(X+1). Let’s call this DP. Fill ...read more
CodingNinjas
author
2y
Iterative DP
  1. Create an array of the vector of size m+1. Let’s call it weights, and add each weight of i’th color at the index i.
  2. Create a 2D boolean array of size (M+1)*(X+1). Let’s call this DP.
  3. Initial...read more
Add answer anonymously...
Dell Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter