Files

42 lines
1.4 KiB
Java
Raw Permalink Normal View History

2017-03-24 00:02:30 -05:00
// Author: Rodney Shaghoulian
2018-07-27 16:45:56 -07:00
// Github: github.com/RodneyShag
// HackerRank: hackerrank.com/RodneyShag
2017-03-24 00:02:30 -05:00
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
2017-04-07 20:17:38 -05:00
// Algorithm: Eat the largest cupcakes first
// Is this a Greedy Algorithm? No.
//
// A greedy algorithm makes the "locally optimal choice at each stage with the hope of finding a
// global optimum" - Wikipedia. Our solution actually makes the locally LEAST optimal choice at
// each stage, so it is not a greedy algorithm. Is there a name for this approach? I'm not sure,
// but maybe we can call it a "reverse-greedy algorithm"
2017-04-05 18:42:35 -05:00
// Time Complexity: O(n log n)
2017-03-24 00:02:30 -05:00
public class Solution {
2017-09-11 09:32:17 -07:00
public static void main(String[] args) {
2017-03-24 00:02:30 -05:00
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
2017-04-07 20:17:38 -05:00
Integer [] calories = new Integer[n]; // Use Integer instead of int to make sorting in simpler
2017-03-24 00:02:30 -05:00
for (int i = 0; i < n; i++){
calories[i] = scan.nextInt();
}
scan.close();
System.out.println(minimumMiles(calories));
}
private static long minimumMiles(Integer [] calories) {
Arrays.sort(calories, Collections.reverseOrder());
long multiplier = 1;
long miles = 0;
for (int j = 0; j < calories.length; j++) {
miles += calories[j] * multiplier;
multiplier *= 2;
}
return miles;
}
}