Open In App

Minimum, maximum and average price values for all the items of given type

Given a string array item[] and an integer array price[] where price[i] is the price of the item[i] when purchased from the ith shop. The task is find the lowest, the highest and the average price value for all the purchased items. 

Examples:

Input: item[] = {“toy”, “pen”, “notebook”, “pen”}, price[] = {2, 1, 3, 2} 
Output: Item Min Max Average pen 1 2 1.5 toy 2 2 2.0 notebook 3 3 3.0 

Input: item[] = {“car”, “car”}, price[] = {20000, 30000}; 
Output: Item Min Max Average car 20000 30000 25000.0

Approach: Create a HashMap where the name of the item will be a string and the value will be an object which will store four types of values for every item i.e.

  1. min: To store the minimum value for an item of current type.
  2. max: To store the maximum value for an item of current type.
  3. total: Total item of the current type.
  4. sum: Sum of the prices of the items of current type.

Now, for every item stored in the Hashmap, the minimum and the maximum price is store in the value object and the average can be calculated as sum / total. Below is the implementation of the above approach: 




#include <bits/stdc++.h>
using namespace std;
 
// Class to store an item
class Item {
public:
    int min; // To store the minimum price for the item
    int max; // To store the maximum price for the item
    int total; // To store the total number of items of the
               // current type
    int sum; // To store the total cost of buying the items
 
    // Initializing an element with default values
    Item()
        : min(0)
        , max(0)
        , total(0)
        , sum(0)
    {
    }
 
    // Initializing an element with a price
    Item(int price)
        : min(price)
        , max(price)
        , total(1)
        , sum(price)
    {
    }
};
 
// Function to find the minimum, maximum, and average price
// for every item
void findPrices(const vector<string>& item,
                const vector<int>& price, int n)
{
    unordered_map<string, Item> itemMap;
 
    // For every item
    for (int i = 0; i < n; ++i) {
        // If the current item has already been purchased
        // earlier from a different shop
        if (itemMap.find(item[i]) != itemMap.end()) {
            // Get the item
            Item& currItem = itemMap[item[i]];
 
            // Update its minimum and maximum price so far
            currItem.min = min(currItem.min, price[i]);
            currItem.max = max(currItem.max, price[i]);
 
            // Increment the total count of the current item
            currItem.total += 1;
 
            // Add the current price to the sum
            currItem.sum += price[i];
        }
        else {
            // The item has been purchased for the first
            // time
            itemMap[item[i]] = Item(price[i]);
        }
    }
 
    // Print all the items with their minimum, maximum, and
    // average prices
    cout << "Item Min Max Average" << endl;
    for (const auto& pair : itemMap) {
        const string& key = pair.first;
        const Item& currItem = pair.second;
        cout << key << " " << currItem.min << " "
             << currItem.max << " "
             << ((float)currItem.sum / (float)currItem.total) << endl;
    }
}
 
// Driver code
int main()
{
    vector<string> item
        = { "toy", "pen", "notebook", "pen" };
    int n = item.size();
    vector<int> price = { 2, 1, 3, 2 };
 
    findPrices(item, price, n);
 
    return 0;
}




// Java implementation of the approach
import java.util.*;
class GFG {
 
    // To store an item
    static class Item {
 
        // To store the minimum and the
        // maximum price for the item
        int min, max;
 
        // To store the total number of items
        // of the current type and the
        // total cost of buying them
        int total, sum;
 
        // Initializing an element
        Item(int price)
        {
            min = price;
            max = price;
            total = 1;
            this.sum = price;
        }
    }
 
    // Function to find the minimum, the maximum
    // and the average price for every item
    static void findPrices(String item[], int price[], int n)
    {
 
        // To store the distinct items
        HashMap<String, Item> map = new HashMap<>();
 
        // For every item
        for (int i = 0; i < n; i++) {
 
            // If the current item has already been
            // purchased earlier from a different shop
            if (map.containsKey(item[i])) {
 
                // Get the item
                Item currItem = map.get(item[i]);
 
                // Update its minimum and maximum price so far
                currItem.min = Math.min(currItem.min, price[i]);
                currItem.max = Math.max(currItem.max, price[i]);
 
                // Increment the total count of the current item
                currItem.total++;
 
                // Add the current price to the sum
                currItem.sum += price[i];
            }
            else {
 
                // The item has been purchased for the first time
                Item currItem = new Item(price[i]);
                map.put(item[i], currItem);
            }
        }
 
        // Print all the items with their
        // minimum, maximum and average prices
        System.out.println("Item Min Max Average");
        for (Map.Entry<String, Item> ob : map.entrySet()) {
            String key = ob.getKey();
            Item currItem = ob.getValue();
            System.out.println(key + " " + currItem.min
                               + " " + currItem.max + " "
                               + ((float)currItem.sum / (float)currItem.total));
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        String item[] = { "toy", "pen", "notebook", "pen" };
        int n = item.length;
        int price[] = { 2, 1, 3, 2 };
 
        findPrices(item, price, n);
    }
}




# Python implementation of the approach
import math
 
# To store an item
class Item:
 
    # To store the minimum and the
    # maximum price for the item
    min = 0
    max = 0
 
    # To store the total number of items
    # of the current type and the
    # total cost of buying them
    total = 0
    sum = 0
 
    # Initializing an element
    def __init__(self, price):
        self.min = price
        self.max = price
        self.total = 1
        self.sum = price
 
# Function to find the minimum, the maximum
# and the average price for every item
 
 
def findPrices(item, price, n):
 
    # To store the distinct items
    map = {}
 
    # For every item
    for i in range(n):
 
        # If the current item has already been
        # purchased earlier from a different shop
        if item[i] in map:
 
            # Get the item
            currItem = map.get(item[i])
 
            # Update its minimum and maximum price so far
            currItem.min = min(currItem.min, price[i])
            currItem.max = max(currItem.max, price[i])
 
            # Increment the total count of the current item
            currItem.total += 1
 
            # Add the current price to the sum
            currItem.sum += price[i]
        else:
 
            # The item has been purchased for the first time
            currItem = Item(price[i])
            map[item[i]] = currItem
 
    # Print all the items with their
    # minimum, maximum and average prices
    print("Item Min Max Average")
    for key, currItem in map.items():
        print(key, currItem.min, currItem.max,
              (currItem.sum / currItem.total))
 
# Driver code
if __name__ == "__main__":
    item = ["toy", "pen", "notebook", "pen"]
    n = len(item)
    price = [2, 1, 3, 2]
 
    findPrices(item, price, n)




// C# implementation of the approach
using System;        
using System.Collections.Generic;
 
class GFG
{
 
    // To store an item
    public class Item
    {
 
        // To store the minimum and the
        // maximum price for the item
        public int min, max;
 
        // To store the total number of items
        // of the current type and the
        // total cost of buying them
        public int total, sum;
 
        // Initializing an element
        public Item(int price)
        {
            min = price;
            max = price;
            total = 1;
            this.sum = price;
        }
    }
 
    // Function to find the minimum, the maximum
    // and the average price for every item
    static void findPrices(String []item,
                              int []price, int n)
    {
 
        // To store the distinct items
        Dictionary<String,
                   Item> map = new Dictionary<String,
                                              Item>();
 
        // For every item
        for (int i = 0; i < n; i++)
        {
 
            // If the current item has already been
            // purchased earlier from a different shop
            if (map.ContainsKey(item[i]))
            {
 
                // Get the item
                Item currItem = map[item[i]];
 
                // Update its minimum and
                // maximum price so far
                currItem.min = Math.Min(currItem.min,
                                           price[i]);
                currItem.max = Math.Max(currItem.max,
                                           price[i]);
 
                // Increment the total count of
                // the current item
                currItem.total++;
 
                // Add the current price to the sum
                currItem.sum += price[i];
            }
            else
            {
 
                // The item has been purchased
                // for the first time
                Item currItem = new Item(price[i]);
                map.Add(item[i], currItem);
            }
        }
 
        // Print all the items with their
        // minimum, maximum and average prices
        Console.WriteLine("Item Min Max Average");
        foreach(KeyValuePair<String, Item> ob in map)
        {
            String key = ob.Key;
            Item currItem = ob.Value;
            Console.WriteLine(key + " " + currItem.min +
                                    " " + currItem.max +
                                    " " + ((float)currItem.sum /
                                           (float)currItem.total));
        }
    }
 
    // Driver code
    public static void Main(String []args)
    {
        String []item = { "toy", "pen", "notebook", "pen" };
        int n = item.Length;
        int []price = { 2, 1, 3, 2 };
 
        findPrices(item, price, n);
    }
}
 
// This code is contributed by 29AjayKumar




// To store an item
class Item
{
 
  // To store the minimum and the
  // maximum price for the item
  constructor(price) {
    this.min = price;
    this.max = price;
    this.total = 1;
    this.sum = price;
  }
}
 
// Function to find the minimum, the maximum
// and the average price for every item
function findPrices(item, price, n) {
  // To store the distinct items
  const map = new Map();
 
  // For every item
  for (let i = 0; i < n; i++) {
    // If the current item has already been
    // purchased earlier from a different shop
    if (map.has(item[i])) {
      // Get the item
      const currItem = map.get(item[i]);
 
      // Update its minimum and maximum price so far
      currItem.min = Math.min(currItem.min, price[i]);
      currItem.max = Math.max(currItem.max, price[i]);
 
      // Increment the total count of the current item
      currItem.total += 1;
 
      // Add the current price to the sum
      currItem.sum += price[i];
    } else {
      // The item has been purchased for the first time
      const currItem = new Item(price[i]);
      map.set(item[i], currItem);
    }
  }
 
  // Print all the items with their
  // minimum, maximum and average prices
  console.log("Item Min Max Average");
  for (const [key, currItem] of map) {
    console.log(key, currItem.min, currItem.max, currItem.sum / currItem.total);
  }
}
 
// Driver code
const item = ["toy", "pen", "notebook", "pen"];
const n = item.length;
const price = [2, 1, 3, 2];
findPrices(item, price, n);
 
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL

Output
Item Min Max Average
pen 1 2 1.5
toy 2 2 2.0
notebook 3 3 3.0

Time complexity: O(n).

Space complexity : O(k), where k is the number of distinct items.


Article Tags :