Skip to content

Commit e6c2bcc

Browse files
committed
Problem 084 Greed Florist
1 parent 7cda8de commit e6c2bcc

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package hackerRank_JavaProblemSolving;
2+
3+
import java.io.BufferedWriter;
4+
import java.io.FileWriter;
5+
import java.io.IOException;
6+
import java.util.Arrays;
7+
import java.util.Scanner;
8+
9+
public class Problem084_GreedyFlorist {
10+
11+
// IDEAS : Poorly worded explanation, no discussion about sorting or sorted cost array
12+
// CREDITS : Reno Lu from Forum Discussion https://www.hackerrank.com/renolu?hr_r=1
13+
static int getMinimumCost(int k, int[] c, int size) {
14+
Arrays.sort(c);
15+
int totalCost = 0;
16+
if ( k == size) { // Simple case , no need to O(n*k) , purely O(n)
17+
for ( int cost : c) {
18+
totalCost += cost;
19+
}
20+
return totalCost;
21+
}
22+
else {
23+
int i = size-1;
24+
int bought = 0;
25+
// Start backwards from the most expensive flower, stop when there is no more flowers left
26+
while (i >= 0) {
27+
//Calculate total
28+
//increment bought by 1 when everyone in the group has bought equal number of flowers
29+
for(int j=0; j<k && i >= 0; j++){
30+
totalCost+=(1+bought)*c[i];
31+
i--;
32+
}
33+
bought++;
34+
}
35+
}
36+
return totalCost; // For complex case
37+
}
38+
39+
40+
private static final Scanner scanner = new Scanner(System.in);
41+
42+
public static void main(String[] args) throws IOException {
43+
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
44+
45+
String[] nk = scanner.nextLine().split(" ");
46+
47+
int n = Integer.parseInt(nk[0]);
48+
49+
int k = Integer.parseInt(nk[1]);
50+
51+
int[] c = new int[n];
52+
53+
String[] cItems = scanner.nextLine().split(" ");
54+
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
55+
56+
for (int i = 0; i < n; i++) {
57+
int cItem = Integer.parseInt(cItems[i]);
58+
c[i] = cItem;
59+
}
60+
61+
int minimumCost = getMinimumCost(k, c, n);
62+
63+
// TEST CASE 1 , input 50 3 and
64+
// int[] tc1 = {390225,426456,688267,800389,990107,439248,240638,15991,874479,568754,729927,980985,132244,488186,5037,721765,251885,28458,23710,281490,30935,897665,768945,337228,533277,959855,927447,941485,24242,684459,312855,716170,512600,608266,779912,950103,211756,665028,642996,262173,789020,932421,390745,433434,350262,463568,668809,305781,815771,550800};
65+
// int minimumCost = getMinimumCost(3, tc1, 50);
66+
67+
bufferedWriter.write(String.valueOf(minimumCost));
68+
bufferedWriter.newLine();
69+
70+
bufferedWriter.close();
71+
72+
scanner.close();
73+
}
74+
}

0 commit comments

Comments
 (0)