(UVA) Shopaholic - Solution
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=2354
The solution bellow used a Greedy approach to solve this problem.
We sort the array of items in a decreasing order and, every 3 items, we sum the value of the last item (the one that would be given for free).
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int numTests = sc.nextInt();
for (int test = 0; test < numTests; test++) {
int numItems = sc.nextInt();
Integer[] items = new Integer[numItems];
for (int i = 0; i < numItems; i++) {
items[i] = sc.nextInt();
}
Arrays.sort(items, Collections.reverseOrder());
int totalDiscount = 0;
for (int i = 2; i < numItems; i += 3) {
totalDiscount += items[i];
}
bw.write(totalDiscount+"\n");
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
The solution bellow used a Greedy approach to solve this problem.
We sort the array of items in a decreasing order and, every 3 items, we sum the value of the last item (the one that would be given for free).
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int numTests = sc.nextInt();
for (int test = 0; test < numTests; test++) {
int numItems = sc.nextInt();
Integer[] items = new Integer[numItems];
for (int i = 0; i < numItems; i++) {
items[i] = sc.nextInt();
}
Arrays.sort(items, Collections.reverseOrder());
int totalDiscount = 0;
for (int i = 2; i < numItems; i += 3) {
totalDiscount += items[i];
}
bw.write(totalDiscount+"\n");
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment