Marc's Cakewalk HackerRank Solution


Marc's Cakewalk HackerRank Solution
Source : https://www.hackerrank.com/challenges/marcs-cakewalk



Source : https://www.hackerrank.com/challenges/marcs-cakewalk


Solution


// Karthikalapati.blogspot.com
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
// 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"
// Time Complexity: O(n log n)
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Integer [] calories = new Integer[n]; // Use Integer instead of int to make sorting in simpler
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;
}
}

3 comments:

  1. Not working for test case
    40
    819 701 578 403 50 400 983 665 510 523 696 532 51 449 333 234 958 460 277 347 950 53 123 227 646 190 938 61 409 110 61 178 659 989 625 237 944 550 954 439

    expected ans 59715404338867

    ReplyDelete
    Replies
    1. python 3.7

      n = int(input().strip())

      calories = input().strip().split()
      calories = map(int, calories)
      calories = list(calories)
      calories.sort(reverse=True)

      total = [cal * 2**idx for idx, cal in enumerate(calories)]
      total = sum(total)

      print(total)

      Delete
    2. Python 3.7

      n = int(input().strip())

      calories = input().strip().split()
      calories = map(int, calories)
      calories = list(calories)
      calories.sort(reverse=True)

      total = [cal * 2**idx for idx, cal in enumerate(calories)]
      total = sum(total)

      print(total)

      Delete