-
Notifications
You must be signed in to change notification settings - Fork 2
/
Solution.java
68 lines (51 loc) · 1.52 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package hackrank.algorithm.greedy.flowers;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
/**
* Flowers Challenge
*
* @see https://www.hackerrank.com/challenges/flowers
*/
public class Solution {
public static void main(String[] args) {
FlowerShop flowerShop = readInput(System.in);
System.out.println(calculateTotalPurchase(flowerShop));
}
public static int calculateTotalPurchase(FlowerShop shop) {
Collections.sort(shop.prices, Collections.reverseOrder());
int total = 0;
int multiplier = 0;
int personIndex = 0;
for (int price : shop.prices) {
total += (multiplier + 1) * price;
personIndex++;
if (personIndex == shop.people) {
personIndex = 0;
multiplier++;
}
}
return total;
}
public static FlowerShop readInput(InputStream stream) {
Scanner scanner = new Scanner(stream);
int size = scanner.nextInt();
int people = scanner.nextInt();
List<Integer> prices = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
prices.add(scanner.nextInt());
}
scanner.close();
return new FlowerShop(people, prices);
}
}
class FlowerShop {
int people;
List<Integer> prices;
FlowerShop(int people, List<Integer> prices) {
this.people = people;
this.prices = prices;
}
}