Marc's Cakewalk hackerrank Solution

Published on September 02, 2021
Last updated September 02, 2021

Marc loves cupcakes, but he also likes to stay fit. Each cupcake has a calorie count, and Marc can walk a distance to expend those calories. If Marc has eaten j cupcakes so far, after eating a cupcake with c calories he must walk at least pow(2, j) * c miles to maintain his weight.

Function Description

Complete the marcsCakewalk function in the editor below.

marcsCakewalk has the following parameter(s):

  • int calorie[n]: the calorie counts for each cupcake

Returns

  • long: the minimum miles necessary

Input Format

The first line contains an integer n, the number of cupcakes in calorie. The second line contains n space-separated integers, calorie[i].

Marc’s Cakewalk Solution in java


// MarcsCakewalk
import java.util.Arrays;
import java.util.Scanner;

class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int arr[] = new int[n];
        for (int i = 0; i < n; i++)
            arr[i] = sc.nextInt();

        Arrays.sort(arr);
        long res = 0;
        for (int i = 0; i < n; i++) {
            res += (long) (Math.pow(2, i) * arr[n - i - 1]);
        }
        System.out.println(res);
        sc.close();
    }
}


Tags :