Colorful Knapsack Problem

You are given a set of 'N' stones, each with a specific weight and color. The goal is to fill a knapsack with exactly 'M' stones, choosing one stone of each color, so that the total weight does not exceed a given capacity 'X'. The objective is to minimize the unused capacity of the knapsack.

Input:

The first line contains three integers 'N', 'M', and 'X', separated by spaces, where:
- N is the total number of stones,
- M is the number of distinct colors,
- X is the total weight capacity of the knapsack.
The second line contains N integers representing the weights of the stones: W[1], W[2], ..., W[N].
The third line contains N integers representing the colors of the stones: C[1], C[2], ..., C[N].

Output:

Output a single integer: the minimum unused capacity of the knapsack. If the knapsack cannot be filled under the given conditions, output -1.

Example:

Assume the following input:

5 3 10
4 5 3 8 2
1 2 3 3 1

The output should be:

1

Constraints:

  • 1 <= M <= N <= 100
  • 1 <= X <= 10000
  • 1 <= W[i] <= 100
  • 1 <= C[i] <= M
  • Time Limit: 1 sec

Note:

Focus on minimizing the unused capacity after selecting one stone of each color.

AnswerBot
4mo

The Colorful Knapsack Problem involves selecting one stone of each color to fill a knapsack with a given weight capacity, minimizing unused capacity.

  • Iterate through the stones and keep track of the mi...read more

Help your peers!
Select
Add answer anonymously...

Top Android Developer Interview Questions Asked at Paytm

Q. Given an array, write a function to move all 0's to the end of it while maintain...read more
Q. Why is Dagger required?
Q. How does garbage collection work?
Android Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits