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.
If Marc has eaten cupcakes so far, after eating a cupcake with calories he must walk at least miles to maintain his weight.
Example 1:
Input: 3
1 3 2
Output: 11
Approach
Java
import java.util.Arrays;import java.util.Scanner;public class MarcsCakewalk {public static void main(String[] args) {Scanner in = new Scanner(System.in);long n = in.nextLong();long arr[] = new long[(int) n];for (int i = 0; i < n; i++)arr[i] = in.nextLong();long ans = 0;Arrays.sort(arr);for (int i = (int) n - 1; i >= 0; i--) {ans = ans + arr[i] * power((long) 2, n - i - 1);}System.out.println(ans);in.close();}static long power(long a, long n) {// Base Caseif (n == 0)return 1;long res = power(a, n / 2);if (n % 2 == 1)return res * res * a;elsereturn res * res;}}
C++
#include <bits/stdc++.h>using namespace std;//Function to find power(a,n)long long int power(long long int a,long long int n){//Base Caseif(n==0)return 1;long long int res=power(a,n/2);if(n&1)return res*res*a;elsereturn res*res;}int main(){long long int n;cin>>n;long long int arr[n];for(long long int i=0;i<n;i++)cin>>arr[i];long long int ans=0;sort(arr,arr+n,greater<>());for(long long int i=0;i<n;i++){ans=ans+arr[i]*power(2,i);}cout<<ans<<"\n";return 0;}//Time Complexity: O(nlog(n))
✌️✌️
ReplyDelete