C++ Coding Exercise - Maximum unit to load into a truck given it size You are assigned to put some amount of boxes onto one truck. You are given a 2D vector of box_types where box_type[0] is the number of a type of box and box_type[1] is the units per box for that type. You are also given an integer value for the truck size, this the maximum boxes you can put in the truck. Return the maximum unit that can be put in a given truck.
Example
input : box_types = {{1, 3}, {2, 2}, {3, 1}}
truck_size = 4
output: 8
Explanation:
There are

1 box of type 0
2 box of type 1
3 box of type 2

where 0, 1, 2 is the index of the vector
You can take all the boxes of the first type, second type and one box from the third type
max_unit = (1 * 3) + (2 * 2) + (1 * 1) = 8
Here is my implementation
#include &lt;iostream&gt;
#include &lt;algorithm&gt;
#include &lt;vector&gt;

void sort_boxtypes(std::vector&lt;std::vector&lt;int&gt;&gt; &amp;box_types)
{
    std::sort(
        box_types.begin(), box_types.end(), 
        [](const std::vector&lt;int&gt;&amp; a, const std::vector&lt;int&gt; &amp;b)
        {return a[1] &gt; b[1]; }
    );
}
int maximum_units(std::vector&lt;std::vector&lt;int&gt;&gt; box_types, int truck_size)
{
    sort_boxtypes(box_types);
    int max_unit = 0;
    for(const auto&amp; box_type : box_types)
    {
        truck_size -= box_type[0];
        if(truck_size &gt;= 0)
            max_unit += box_type[0] * box_type[1];
        else
        {
            max_unit += (box_type[0] + truck_size) * box_type[1];
            return max_unit;
        } 
    }
    return max_unit;
}

int main()
{
    std::vector&lt;std::vector&lt;int&gt;&gt; box_types = {{5, 10}, {2, 5}, {4, 7}, {3, 9}};
    int max = maximum_units(box_types, 10);
    std::cout &lt;&lt; max &lt;&lt; '\n';
    
}
Names are better then indices. Consider
  struct box_type {
      int amount;
      int capacity;
  };

box.amount seems cleaner that box[0].

Along the same line, declaring such a structure would let you define
  friend bool box_type::operator &lt;(const box_type&amp; l, const box_type&amp; r) {
      return l.capacity &lt; r.capacity;
  }

and eliminate a lambda, as well as sort_boxtypes function.

I don't like max_units (it sounds like there are min_units somewhere). Similarly, truck_size is a truck size, a constant; consider a remaining_size or something like that.

It feels that a truck_size &gt;= 0 comparison shall be done beforehand. Consider
  std::sort(boxes.begin(), boxes.end());
  for (auto box = boxes.rbegin(); box != boxes.rend(); ++box) {
      auto the_load = std::min(box.amount, remaining_size());
      units += box.capacity * box.amount;
      remaining_size -= the_load;
      if (remaining_size == 0) {
          break;
      }
  }
  return units;