Knapsack
Problem
What’s Knapsack?
A knapsack is a bag you carry on your back—like a
backpack! It’s a sack you use to hold stuff when you’re
on the move, like going hiking, traveling, or even just to
school. Simple definition: A knapsack is a portable bag
for carrying things, usually on your back.
•“Knap”: Comes from an old Dutch or German word,
knappe or knap, which means "to bite" or "a snack." It’s
like something you’d grab quick—like food!
•“Sack”: From Old English sacc or Germanic sak, just
meaning a bag.
The Knapsack Problem is about packing a bag with stuff. I’ve got:
•Items, each with a weight (how heavy) and a value (how useful or
good).
•A bag with a capacity (max weight it can hold).
•My job: Pick items to get the most total value without going over
the weight limit.
Intention: It’s like a game to make the smartest choices when I can’t
take everything.
The goal is to maximize value while staying within a limit.
What’s The Point of it?
Types of knapsack Problems:
•0/1 Knapsack Problem
•Each item can either be included (1) or not (0)—no fractions allowed.
•Fractional Knapsack Problem
•Items can be broken into smaller parts, i.e., you can take fractions of an item.
•Solved efficiently using Greedy Algorithm in O(n log n) time
Hola! I’m Dora, and Boots and I are treasure hunters in the jungle! My magic
backpack can hold a certain number of kilograms, and we’re collecting
treasures with weights (in kg) and stars (shiny points). I can take whole items
or pieces to get the most stars before Swiper swipes. Our quest: Make a plan
that works for any treasure pile and bag size, all in kilograms!
Question:
Dora Boots BackPack Stars (Value) Swiper
The Quest (Test Data):
•Bag Capacity: 100 kg
•Items:
• Item 1 (Golden Statue): 30 kg, 90 stars
• Item 2 (Crystal Gem): 40 kg, 100 stars
• Item 3 (Magic Map): 50 kg, 120 stars
•Goal: Maximize stars, flexible for any bag and items, measured in kilograms!
Question:
Golden Statue Crystal Gem Magic Map
Stars per Kilogram (Value per Weight)
For any item: Stars ÷ Weight (kg) = Stars per kg.
•Item 1 (Golden Statue): 90 ÷ 30 = 3 stars/kg
•Item 2 (Crystal Gem): 100 ÷ 40 = 2.5 stars/kg
•Item 3 (Magic Map): 120 ÷ 50 = 2.4 stars/kg
I1: 30, 90
I2: 40, 100
I3: 50, 120
We Sort Items:
Now We Sort By Descending Order:
Item1 = 3 stars/kg
Item2 = 2.5 stars/kg
Item3 = 2.4 stars/kg
•Item 1 (30 kg, 90 stars):
•In it goes! 100 - 30 = 70 kg left.
•Stars = 90.
70 kg left.
•Item 2 (40 kg, 100 stars):
•70 - 40 = 30 kg left.
•Stars = 90 + 100 = 190.
30 kg left.
•Item 3 (50 kg, 120 stars): 30 kg left:
• Fraction = 30 ÷ 50 = 3/5
• Stars = (3/5) × 120 = 72
•Total:
• Weight = 30 + 40 + 30 = 100 kg
• Value = 90 + 100 + 72 = 262
0 kg left.
CODE:
This code sets up the foundation for solving the problem using Java’s object-
oriented features. The import java.util.Arrays; statement pulls in the Arrays
class from Java’s utility package, giving me access to its sort method later—
essential for arranging items efficiently.
The public class DoraKnapsackKg defines the main class, which is the
container for my program. It’s public so it’s accessible from anywhere, and
it’s where I’ll put all my knapsack-solving logic.
CODE:
Inside, I define a static class Item—a nested static class that acts as a blueprint
for creating objects representing each item (like a treasure). Being static means I
can instantiate Item objects without needing an instance of DoraKnapsackKg.
The class has three fields:
•int itemWeight: An integer to store the item’s weight in kilograms.
•int itemValue: An integer for the item’s value (stars).
•double valuePerWeight: A double (floating-point number) to hold the value-to-
weight ratio, allowing decimal precision.
CODE:
The Item(int w, int v) constructor is a special method that initializes a new Item
object when I call it with two parameters: w (weight) and v (value), both
integers. Inside the constructor, it assigns these parameters to the object’s
fields and calculates valuePerWeight by dividing v by w, casting the result to
double with (double) to ensure floating-point division (e.g., 90 / 30 = 3.0, not 3).
1.Creates an Array:
It makes a new array called items that can hold numItems elements of type
Item.
2.Fills the Array:
It uses a for loop to go through each index from 0 to numItems - 1. For each
index i, it creates a new Item using itemWeights[i] and itemValues[i] as the
weight and value, respectively, and then stores that new Item in the array at
that index.
CODE:
This line sorts the items array in descending order based on each item's
valuePerWeight:
•Arrays.sort(items, ...):
It sorts the array named items.
•Lambda Comparator
•(a, b) -> Double.compare(b.valuePerWeight, a.valuePerWeight):
This is a custom comparison that compares two Item objects, a and b.
•It calls Double.compare(b.valuePerWeight, a.valuePerWeight), which
compares the valuePerWeight of b with that of a.
•Because b is compared to a (not a to b), the sorting will be in
descending order: items with higher valuePerWeight come first.
CODE:
CODE:
These two lines initialize two variables:
•double totalValue = 0.0;
This creates a variable to keep track of the total value of
the items added to the knapsack, starting at zero.
•int weightLoaded = 0;
This variable will track the total weight of the items loaded
into the bag, also starting at zero.
CODE:
This loop goes through each item and adds as much of it as possible to the bag:
•For each item:
The loop checks if the bag can fit the entire item.
•If yes:
It adds the item's full value to totalValue, reduces bagCapacity by the item's weight, and increases
weightLoaded by the item's weight.
•If no:
It calculates how much of the item can be added as a fraction. Then, it adds that fractional value to
totalValue, increases weightLoaded by the remaining capacity, and stops adding more items (breaks the
loop).
CODE:
•System.out.println("Weight Loaded: " + weightLoaded + " kg");
This prints the total weight that was actually loaded into the bag.
•return totalValue;
This returns the maximum value that can be obtained with the given
bag capacity.
CODE:
itemWeights1 and itemValues1 are arrays holding the weights and values of
three items.
bagCapacity1 defines the bag's capacity (100 kg).
numItems1 indicates the number of items (3).
line calls the fractionalKnapsack method with the test data and stores the
returned maximum value in maxValue1.
Finally, last line prints the maximum value that the knapsack can hold,
based on the given items and capacity.
CODE:
OUTPUT:

Fractional Knapsack Problem with Dora Example in Java

  • 1.
  • 2.
    What’s Knapsack? A knapsackis a bag you carry on your back—like a backpack! It’s a sack you use to hold stuff when you’re on the move, like going hiking, traveling, or even just to school. Simple definition: A knapsack is a portable bag for carrying things, usually on your back. •“Knap”: Comes from an old Dutch or German word, knappe or knap, which means "to bite" or "a snack." It’s like something you’d grab quick—like food! •“Sack”: From Old English sacc or Germanic sak, just meaning a bag.
  • 3.
    The Knapsack Problemis about packing a bag with stuff. I’ve got: •Items, each with a weight (how heavy) and a value (how useful or good). •A bag with a capacity (max weight it can hold). •My job: Pick items to get the most total value without going over the weight limit. Intention: It’s like a game to make the smartest choices when I can’t take everything. The goal is to maximize value while staying within a limit. What’s The Point of it?
  • 4.
    Types of knapsackProblems: •0/1 Knapsack Problem •Each item can either be included (1) or not (0)—no fractions allowed. •Fractional Knapsack Problem •Items can be broken into smaller parts, i.e., you can take fractions of an item. •Solved efficiently using Greedy Algorithm in O(n log n) time
  • 5.
    Hola! I’m Dora,and Boots and I are treasure hunters in the jungle! My magic backpack can hold a certain number of kilograms, and we’re collecting treasures with weights (in kg) and stars (shiny points). I can take whole items or pieces to get the most stars before Swiper swipes. Our quest: Make a plan that works for any treasure pile and bag size, all in kilograms! Question: Dora Boots BackPack Stars (Value) Swiper
  • 6.
    The Quest (TestData): •Bag Capacity: 100 kg •Items: • Item 1 (Golden Statue): 30 kg, 90 stars • Item 2 (Crystal Gem): 40 kg, 100 stars • Item 3 (Magic Map): 50 kg, 120 stars •Goal: Maximize stars, flexible for any bag and items, measured in kilograms! Question: Golden Statue Crystal Gem Magic Map
  • 7.
    Stars per Kilogram(Value per Weight) For any item: Stars ÷ Weight (kg) = Stars per kg. •Item 1 (Golden Statue): 90 ÷ 30 = 3 stars/kg •Item 2 (Crystal Gem): 100 ÷ 40 = 2.5 stars/kg •Item 3 (Magic Map): 120 ÷ 50 = 2.4 stars/kg I1: 30, 90 I2: 40, 100 I3: 50, 120 We Sort Items: Now We Sort By Descending Order: Item1 = 3 stars/kg Item2 = 2.5 stars/kg Item3 = 2.4 stars/kg
  • 8.
    •Item 1 (30kg, 90 stars): •In it goes! 100 - 30 = 70 kg left. •Stars = 90. 70 kg left.
  • 9.
    •Item 2 (40kg, 100 stars): •70 - 40 = 30 kg left. •Stars = 90 + 100 = 190. 30 kg left.
  • 10.
    •Item 3 (50kg, 120 stars): 30 kg left: • Fraction = 30 ÷ 50 = 3/5 • Stars = (3/5) × 120 = 72 •Total: • Weight = 30 + 40 + 30 = 100 kg • Value = 90 + 100 + 72 = 262 0 kg left.
  • 11.
    CODE: This code setsup the foundation for solving the problem using Java’s object- oriented features. The import java.util.Arrays; statement pulls in the Arrays class from Java’s utility package, giving me access to its sort method later— essential for arranging items efficiently. The public class DoraKnapsackKg defines the main class, which is the container for my program. It’s public so it’s accessible from anywhere, and it’s where I’ll put all my knapsack-solving logic.
  • 12.
    CODE: Inside, I definea static class Item—a nested static class that acts as a blueprint for creating objects representing each item (like a treasure). Being static means I can instantiate Item objects without needing an instance of DoraKnapsackKg. The class has three fields: •int itemWeight: An integer to store the item’s weight in kilograms. •int itemValue: An integer for the item’s value (stars). •double valuePerWeight: A double (floating-point number) to hold the value-to- weight ratio, allowing decimal precision.
  • 13.
    CODE: The Item(int w,int v) constructor is a special method that initializes a new Item object when I call it with two parameters: w (weight) and v (value), both integers. Inside the constructor, it assigns these parameters to the object’s fields and calculates valuePerWeight by dividing v by w, casting the result to double with (double) to ensure floating-point division (e.g., 90 / 30 = 3.0, not 3).
  • 14.
    1.Creates an Array: Itmakes a new array called items that can hold numItems elements of type Item. 2.Fills the Array: It uses a for loop to go through each index from 0 to numItems - 1. For each index i, it creates a new Item using itemWeights[i] and itemValues[i] as the weight and value, respectively, and then stores that new Item in the array at that index. CODE:
  • 15.
    This line sortsthe items array in descending order based on each item's valuePerWeight: •Arrays.sort(items, ...): It sorts the array named items. •Lambda Comparator •(a, b) -> Double.compare(b.valuePerWeight, a.valuePerWeight): This is a custom comparison that compares two Item objects, a and b. •It calls Double.compare(b.valuePerWeight, a.valuePerWeight), which compares the valuePerWeight of b with that of a. •Because b is compared to a (not a to b), the sorting will be in descending order: items with higher valuePerWeight come first. CODE:
  • 16.
    CODE: These two linesinitialize two variables: •double totalValue = 0.0; This creates a variable to keep track of the total value of the items added to the knapsack, starting at zero. •int weightLoaded = 0; This variable will track the total weight of the items loaded into the bag, also starting at zero.
  • 17.
    CODE: This loop goesthrough each item and adds as much of it as possible to the bag: •For each item: The loop checks if the bag can fit the entire item. •If yes: It adds the item's full value to totalValue, reduces bagCapacity by the item's weight, and increases weightLoaded by the item's weight. •If no: It calculates how much of the item can be added as a fraction. Then, it adds that fractional value to totalValue, increases weightLoaded by the remaining capacity, and stops adding more items (breaks the loop).
  • 18.
    CODE: •System.out.println("Weight Loaded: "+ weightLoaded + " kg"); This prints the total weight that was actually loaded into the bag. •return totalValue; This returns the maximum value that can be obtained with the given bag capacity.
  • 19.
    CODE: itemWeights1 and itemValues1are arrays holding the weights and values of three items. bagCapacity1 defines the bag's capacity (100 kg). numItems1 indicates the number of items (3). line calls the fractionalKnapsack method with the test data and stores the returned maximum value in maxValue1. Finally, last line prints the maximum value that the knapsack can hold, based on the given items and capacity.
  • 20.
  • 22.