We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Greedy
- Marc's Cakewalk
- Discussions
Marc's Cakewalk
Marc's Cakewalk
+ 0 comments This is my java 8 solution, feel free to ask me any questions.
First lookpublic static long marcsCakewalk(List<Integer> calorie) { //Perform sort the given calories calorie.sort(null); calorie.sort(Collections.reverseOrder()); long sumCalories = 0; //Calculate sum calories for(int i = 0; i < calorie.size(); i++) { long current = (long)Math.pow(2, i) * calorie.get(i); sumCalories = sumCalories + current; } return sumCalories; }
Second look (little bit changed using bitwise manipulation)
long current = (1L << i) * calorie.get(i);
+ 0 comments This is my solution in JavaScript
function marcsCakewalk(calorie) { // Write your code here var result = 0 calorie.sort((a, b) => (a > b ? -1 : 1)) for(var i = 0;i < calorie.length;i++){ result += Math.pow(2,i)*calorie[i] } return result }
+ 0 comments Here is my c++ solution, you can watch explanation here : https://youtu.be/RRJoL2vDmZM
long marcsCakewalk(vector<int> calorie) { sort(calorie.begin(), calorie.end(), [](int l, int r){return l > r;}); long ans = 0; for(int i = 0; i < calorie.size(); i++){ ans += pow(2, i) * calorie[i]; } return ans; }
+ 0 comments Here is my c++ solution, you can watch explanation here : https://youtu.be/RRJoL2vDmZM
long marcsCakewalk(vector<int> calorie) { sort(calorie.begin(), calorie.end(), [](int l, int r){return l > r;}); long ans = 0; for(int i = 0; i < calorie.size(); i++){ ans += pow(2, i) * calorie[i]; } return ans; }
+ 0 comments Python 3
def marcsCakewalk(calorie): return sum([(2**i)*w for i,w in enumerate(sorted(calorie, reverse=True))])
Load more conversations
Sort 394 Discussions, By:
Please Login in order to post a comment