Maximum Calories Burnt from Jumps

You are given an integer array heights of length n, where heights[i] denotes the height of the ith block in a workout session.

You start from the ground at height 0. You must jump onto each block exactly once, in any order.

The calories burnt when jumping from height a to height b is: (a−b)2

For the first jump (from ground to the first selected block heights[i]), the calories burnt is: (0 - heights[i])2

After the first jump, you cannot return to the ground.

Return the maximum total calories that can be burnt by choosing the optimal order of jumps.

Example 1:

Input: heights = [2, 8, 5]

Output: 109

Explanation:

An optimal order is [8, 2, 5].

  • Ground → 8 → (0−8) 2 = 64
  • 8 → 2 → (8−2)2 = 36
  • 2 → 5 → (2−5)2 = 9

Total calories burnt = 64 + 36 + 9 = 109.

Example 2:

Input: heights = [1, 4, 6]

Output: 70

Explanation:

Choose order [6, 1, 4].

  • Ground → 6 = 36
  • 6 → 1 = 25
  • 1 → 4 = 9

Total calories burnt = 36 + 25 + 9 = 70.

Now Your Turn!

Pick the correct output for the given input

Input: heights = [2, 5]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ n = heights.length ≤ 105
  • 1 ≤ heights[i] ≤ 105
  • Each block must be visited exactly once.
  • Jumps can be made in any order.
  • The result fits in a 64-bit integer.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
long long maxCaloriesBurnt(vector<int>& heights) {
// Your code goes here
}
};
Test Case

Input:

Heights