In this HackerRank Marc's Cakewalk problem solution we have given the individual calorie counts for each of the cupcakes, determine the minimum number of miles Marc must walk to maintain his weight. Note that he can eat the cupcakes in any order.

Problem solution in Python.

#!/bin/python3

import sys

n = int(input().strip())
cal = list(map(int, input().strip().split(' ')))
# your code goes here
cal.sort()
cal.reverse()

miles=0
for i in range(n):
cup=cal[i]*(2**i)
miles+=cup

print(miles)

{"mode":"full","isActive":false}

Problem solution in Java.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Integer[] calories = new Integer[n];
for(int calories_i=0; calories_i < n; calories_i++){
calories[calories_i] = in.nextInt();
}
List<Integer> calList = Arrays.asList(calories);
Collections.sort(calList, Collections.reverseOrder());

long cals = 0;
for (int i=0;i<calList.size();i++) {
cals += Math.pow(2,i)*calList.get(i);
}
System.out.println(cals);
}
}

{"mode":"full","isActive":false}

Problem solution in C++.

#include <bits/stdc++.h>

using namespace std;

int main(){
int n;
cin >> n;
vector<int> calories(n);
for(int calories_i = 0; calories_i < n; calories_i++){
cin >> calories[calories_i];
}
// your code goes here
sort(calories.begin(),calories.end());
reverse(calories.begin(),calories.end());
long long temp=1,ans=0;
for(int i=0;i<n;i++)
{
ans+=calories[i]*temp;
temp*=2;
}
printf("%lld\n",ans);
return 0;
}

{"mode":"full","isActive":false}

Problem solution in C.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
int n;
scanf("%d",&n);
int a[n];
int i,j,t;
long int c=0;
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(i=0;i<n;i++){
for(j=n-1;j>0;j--){
if(a[j]>a[j-1]){
t=a[j];
a[j]=a[j-1];
a[j-1]=t;
}
}
}
for(int i=0;i<n;i++){
c=c+(a[i]*(pow(2,i)));
}
printf("%ld",c);
return 0;
}

{"mode":"full","isActive":false}