Minimum cost to fill a knapsack with 1 kg and 2 kg weights

Updated

Given a knapsack of maximum capacity n kgs, infinite numbers of weights of 1kg and 2kgs are available. The cost of 1kg weight is a and the cost of 2kg weight is b.
You can fillup this knapsack by choosing any number (possibly 0) of the 1kg and 2kg weights. Each fillup has a cost associated with it.
Your task is to Minimize the total cost of filling up this knapsack.

Examples :

Input :
n=50 kg
Cost of 1kg weight = a = 5
Cost of 2kg weight = b = 6
Output :
Minimum Total Cost = 150
//You can chose 25 2kg weights and 0 1kg weight to have minimum total
cost
//Weight balance : 25*2 + 0*1 = 50kg, satisfied.

Input :
n=10 kg
Cost of 1kg weight = a = 1
Cost of 2kg weight = b = 3
Output :
Minimum Total Cost = 10
//You can chose 10 1kg weights and 0 2kg weights to have minimum total
cost.

This is a mathematical problem. Suppose we take x number of 1kg weights and y number of 2kg weights. Now, this problem reduces to:
Minimize f(x,y)= x*a + y*b with the constraint x*1 + y*2 =n (Weight balance), where a,b and n are given, and x,y are unknowns.
Replacing x by n-2y, we get :
f(y) = (n-2y)*a + y*b = na + y(b-2a).
Now our last task is to find a value of ‘y’ (number of 2kg weights) such that:

  1. y>=0
  2. y<= n/2 ( 2 in denominator is for 2kg weight. Knapsack will overflow if we take more 2kg weights than this much)

In which case will it give minimum cost? Observe f(y).
If b-2a is positive, choose y=0.
If b-2a is negative, we loop from y=n/2 to y>=0 until f(y) is positive. (Or, we take as many 2kg weights we want, keeping in mind that we can’t take negative numbers of 1kg weights).

Implementation :

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n=10; int a=1; int b=3;
    //f(x,y)= x + 3y
    //Constraint : x+2y = 10
    //f(y) = 10*1 + y(3-2*1) = 10 + y
    //(b-2a) is positive, hence to minimize f(y), use y=0
    if(b-2*a > 0)
    {
        cout<<"Min total cost is "<< n*a + (b-2*a)*0;
    }
    //(b-2a) is negative, so we take as many 2kg weights we want. Maximum is (n/2).
    else
    {
        for(int i= n/2;i>=0;i--)
         {          
           if(n*a + (b-2*a)*(i) >=0)
               {
                 cout<<"Min total cost is "<< n*a + (b-2*a)*(i);
                 break;
               }
          }
    }

} 
Comment
Next tutorial
Mithlesh Upadhyay Published 3 Dec 2026 · 3 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials