Skip to content
Snippets Groups Projects
Verified Commit 3de7c5f7 authored by Dmytro Bogatov's avatar Dmytro Bogatov :two_hearts:
Browse files

Add greedy florist problem.

parent 9dad80bd
Branches
No related tags found
No related merge requests found
using System;
namespace CodingInterview.HackerRank
{
/// <summary>
/// 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) * original_price, the next will be (1 + 1) * 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.
///
/// For example, if there are k = 3 friends that want to buy n = 4 flowers that cost c = [1, 2, 3, 4], each will buy one of the flowers priced [2, 3, 4] at the original price.
/// Having each purchased x = 1 flower, the first flower in the list, c[0], will now cost (current_purchase + previous_purchase) * c[0] = (1 + 1) * 1 = 2.
/// The total cost will be 2 + 3 + 4 + 2 = 11.
///
/// https://www.hackerrank.com/challenges/greedy-florist/problem
/// </summary>
public class GreedyFlorist
{
/// <summary>
/// The minimum cost to purchase all of the flowers
/// </summary>
/// <param name="k">an integer, the number of friends</param>
/// <param name="c">an array of integers representing the original price of each flower</param>
/// <returns>the minimum cost to purchase all of the flowers</returns>
public int Solve(int k, int[] c)
{
int result = 0;
Array.Sort(c);
int j = 0;
int multiplier = 0;
for (int i = c.Length - 1; i >= 0; i--)
{
if (j == k)
{
j = 0;
multiplier++;
}
result += c[i] * (multiplier + 1);
j++;
}
return result;
}
}
}
using Xunit;
namespace CodingInterview.Tests.HackerRank
{
public class GreedyFlorist
{
[Fact]
public void TestCases()
{
// From Hacker Rank
Assert.Equal(13, new CodingInterview.HackerRank.GreedyFlorist().Solve(3, new int[] { 2, 5, 6 }));
Assert.Equal(15, new CodingInterview.HackerRank.GreedyFlorist().Solve(2, new int[] { 2, 5, 6 }));
Assert.Equal(29, new CodingInterview.HackerRank.GreedyFlorist().Solve(3, new int[] { 1, 3, 5, 7, 9 }));
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment