blob: 5688cf0e525e7bf309b716b0faf537e2d3229482 (
plain) (
blame)
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
|
package nl.camilstaps.cs;
import java.util.ArrayList;
/**
* Created by camil on 11/28/15.
*/
class CheckoutHelper {
private final ArrayList<Integer> products = new ArrayList<>();
private int minimal_price;
public CheckoutHelper() {
}
private static int round(int cents) throws IllegalArgumentException {
switch (cents % 5) {
case 0: return cents;
case 1: return cents - 1;
case 2: return cents - 2;
case 3: return cents + 2;
case 4: return cents + 1;
}
throw new IllegalArgumentException("Incorrect number of cents.");
}
public int minimumPayment(int dividers) {
int minimums[][] = new int[products.size() + 1][dividers + 1];
int last[][] = new int[products.size() + 1][dividers + 1];
for (int p = 0; p <= products.size(); p++) {
for (int d = 0; d <= dividers; d++) {
if (p == 0) {
minimums[p][d] = 0; // No products
last[p][d] = 0;
} else if (d == 0) {
int sum = 0;
for (int p2 = 0; p < products.size() && p2 < p; p2++)
sum += products.get(p2);
minimums[p][d] = round(sum); // no dividers
last[p][d] = sum;
} else {
int try1 = minimums[p-1][d] - round(last[p-1][d]) + round(last[p-1][d] + products.get(p-1)); // don't place a divider
int try2 = minimums[p-1][d-1] + round(products.get(p-1)); // place a divider
if (try1 < try2) {
minimums[p][d] = try1;
last[p][d] = last[p-1][d] + products.get(p-1);
} else {
minimums[p][d] = try2;
last[p][d] = products.get(p-1);
}
}
}
}
return minimal_price + minimums[products.size()][dividers];
}
public void addProduct(int price) {
int has_to_pay = (price / 5) * 5;
int rest = price % 5;
minimal_price += has_to_pay;
if (rest != 0) {
products.add(rest);
}
}
}
|