Find K items with the lowest values in C++


In this problem, we are given a list that consists of items and their values and an integer k. Our task is to find K items with the lowest values. 

Problem description: We need to find k items from the list that have the lowest value.

Let’s take an example to understand the problem,

Input: item-value = { {item1, 200}, {item2, 100}, {item3, 500}, {item4, 400}} k = 2

Output: item1 , item2

Explanation: 

Two elements with least value are item1 with 200 and item2 with 100.

Solution Approach

A solution to the problem is by finding k items with the least value greedily. We will first sort the item list in ascending order of values. From this sorted list we will find k least value items.

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

bool compVal(pair<string, int> A, pair<string, int> B) {

   if (A.second == B.second)
      return A.first < B.first;
   return A.second < B.second;
}

int main() {

   int k = 2;
   int n = 3;
   vector<pair<string, int> > items;
   items.push_back(make_pair("item1", 350));
   items.push_back(make_pair("item2", 150));
   items.push_back(make_pair("item3", 500));
   items.push_back(make_pair("item4", 100));

   sort(items.begin(), items.end(), compVal);
   
   cout<<k<<" items with least value are \n";
   for (int i = 0; i < min(n, k); ++i)
      cout<<"Item : "<<items[i].first<<", value : "<<items[i].second<<endl;
   return 0;
}

Output

2 items with least value are
Item : item4, value : 100
Item : item2, value : 150

Updated on: 25-Jan-2021

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements