Skip to content
thecscience
THECSICENCE

Learn everything about computer science

  • Home
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
thecscience
THECSICENCE

Learn everything about computer science

HackerRank Greedy Florist Problem Solution

Yashwant Parihar, June 5, 2023August 1, 2024

A group of friends want to buy a bouquet of flowers. The florist wants to maximize his number of new customers and the money he makes. To do this, he decides he’ll multiply the price of each flower by the number of that customer’s previously purchased flowers plus 1. The first flower will be original price, (0+1) x original price, the next will be (1+1) x original price and so on.
Given the size of the group of friends, the number of flowers they want to purchase and the original prices of the flowers, determine the minimum cost to purchase all of the flowers. The number of flowers they want equals the length of the c array.
Example
e = [1, 2, 3, 4]
k = 3
The length of c = 4. so they want to buy 4 flowers total. Each will buy one of the flowers priced [2, 3, 4] at the original price. Having each purchased = 1 flower, the first flower in the list, c[0], will now cost
(current purchase + previous purchases) x c[0] = (1+1) x 1 = 2. The total cost is 2+3+4+2 = 11.

Function Description

Complete the getMinimumCost function in the editor below.

getMinimumCost has the following parameter(s):

  • int c[n]: the original price of each flower
  • int k: the number of friends

Returns
– int: the minimum cost to purchase all flowers

Input Format

The first line contains two space-separated integers n and k, the number of flowers and the number of friends.
The second line contains n space-separated positive integers c[i], the original price of each flower.

Sample Input 0

3 3
2 5 6

Sample Output 0

13
HackerRank Greedy Florist Problem Solution

Greedy Florist C Solution


#include<stdio.h>
#include<stdlib.h>

int compar(const void *, const void *);

int main()
{
	int N,K,x=-1,cost=0;
	scanf(" %d %d",&N, &K);
	int c[N],i;

	for(i=0; i<N; i++)
	{
		scanf(" %d",&c[i]);	
	}

	qsort(c,N,sizeof(int),compar);

	for(i=0; i<N; i++)
	{
		i%K==0?x++:0;	
		cost += (x+1)*c[i];
	}

	printf("%d",cost);

}

int compar(const void *n1, const void *n2)
{
	return -(*(int *)n1 - *(int *)n2);
}

Greedy Florist C++ Solution

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main(void)
{
    int n, k;
    cin >> n >> k;

    vector<int> friends(k, 1);
    vector<int> flowers;
    for (int i = 0; i < n; ++i) {
        int f;
        cin >> f;
        flowers.push_back(f);
    }

    sort(begin(flowers), end(flowers));

    int total = 0;
    while (n --> 0) {
        total += flowers[n] * friends[0];
        ++friends[0];
        make_heap(begin(friends), end(friends), greater<int>());
    }
    cout << total << endl;
}

Greedy Florist C Sharp Solution


/* Sample program illustrating input/output mtehods */
using System;
using System.Collections.Generic;
using System.IO;
class Solution {
        
        static int find_soln(int[] C, int N, int K)
        {
            try
            {
                Array.Sort(C);
                int factor = 0;
                int cost = 0;
                int count = 0, j = 0;
                j = C.Length - 1;
                while (count != N)
                {
                    if (count % K == 0)
                        factor += 1;
                    cost += (C[j] * factor);
                    j--;
                    count++; //Console.WriteLine(N + " " + count + " " + j + " ");
                }
                return cost;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message+" @2");
                return 0;
            }
            
        }
        static void Main(String[] args)
        {
            int N, K;
            string NK = Console.ReadLine();
            string[] NandK = NK.Split(new Char[] { ' ', '\t', '\n' });
            N = Convert.ToInt32(NandK[0]);
            K = Convert.ToInt32(NandK[1]);

            int[] C = new int[N];

            string numbers = Console.ReadLine();
            string[] split = numbers.Split(new Char[] { ' ', '\t', '\n' });

            int i = 0;

            foreach (string s in split)
            {
                if (s.Trim() != "")
                {
                    C[i++] = Convert.ToInt32(s);
                }
            }
            try
            {
                int result = 0;
                result = Solution.find_soln(C, N, K);
                Console.WriteLine(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + " @1");
            }
        }
}

Greedy Florist Java Solution

import java.io.*;
import java.math.*;
import java.util.*;


public class Solution {

    // Complete the getMinimumCost function below.
    static int getMinimumCost(int k, int[] c) {
        int cost =0;
        int size = c.length;
        if(k>=size) return sum(c);
        else{
            // int fix = c[0];
            Arrays.sort(c);
            int i = size-1;
            int last =1;
            while( i>=0){
                for( int j=0;j<k;j++){
                    if(i>=0)
                        cost += (last)*c[i--];
                    else
                        break;
                }
                last++;
            }
        }
        return cost;
    }
    static int sum( int arr[]){
        int sum =0;
        for( int num : arr)
            sum += num;
        return sum;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] nk = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nk[0]);

        int k = Integer.parseInt(nk[1]);

        int[] c = new int[n];

        String[] cItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int cItem = Integer.parseInt(cItems[i]);
            c[i] = cItem;
        }

        int minimumCost = getMinimumCost(k, c);

        bufferedWriter.write(String.valueOf(minimumCost));
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}

Greedy Florist JavaScript Solution

function solve(K, N, c)  {
  var ans = 0;
  var x = 0;
  for (var i = 0; i < K; i++) {
    x = x + (i % N == 0 ? 1 : 0);
    ans += x * c[i];
  }
  console.log(ans);
}

var fs = require('fs');
var cols = fs.readFileSync('/dev/stdin', 'utf-8').split('\n').map(function(l) {
  return l.split(' ').map(function(col) {
    return parseInt(col);
  });
});
cols[1].sort(function(l, r) {
  return l > r;
});
solve(
  cols[0][0],
  cols[0][1],
  cols[1].sort(function(l, r) {
    return r - l;
  })
);

Greedy Florist Python Solution

nflowers, nfriends = (int(x) for x in input().split())
prices = list(map(int, input().split()))
prices.sort(reverse=True)
to_pay = 0
for i in range(nflowers):
    x = i // nfriends
    price = (x+1)*prices[i]
    to_pay += price
print(to_pay)
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post
  • HackerRank Dynamic Array Problem Solution
  • HackerRank 2D Array – DS Problem Solution
  • Hackerrank Array – DS Problem Solution
  • Von Neumann and Harvard Machine Architecture
  • Development of Computers
©2025 THECSICENCE | WordPress Theme by SuperbThemes