Maximum Calories Burnt from Jumps Problem
Description
LeetCode Problem 3730.
You are given an integer array heights of size n, where heights[i] represents the height of the i^th block in an exercise routine.
You start on the ground (height 0) and must jump onto each block exactly once in any order.
- The calories burned for a jump from a block of height
ato a block of heightbis(a - b)^2. - The calories burned for the first jump from the ground to the chosen first block
heights[i]is(0 - heights[i])^2.
Return the maximum total calories you can burn by selecting an optimal jumping sequence.
Note: Once you jump onto the first block, you cannot return to the ground.
Example 1:
Input: heights = [1,7,9]
Output: 181
Explanation:
The optimal sequence is [9, 1, 7].
- Initial jump from the ground to heights[2] = 9: (0 - 9)^2 = 81.
- Next jump to heights[0] = 1: (9 - 1)^2 = 64.
- Final jump to heights[1] = 7: (1 - 7)^2 = 36.
Total calories burned = 81 + 64 + 36 = 181.
Example 2:
Input: heights = [5,2,4]
Output: 38
Explanation:
The optimal sequence is [5, 2, 4].
- Initial jump from the ground to heights[0] = 5: (0 - 5)^2 = 25.
- Next jump to heights[1] = 2: (5 - 2)^2 = 9.
- Final jump to heights[2] = 4: (2 - 4)^2 = 4.
Total calories burned = 25 + 9 + 4 = 38.
Example 3:
Input: heights = [3,3]
Output: 9
Explanation:
The optimal sequence is [3, 3].
- Initial jump from the ground to heights[0] = 3: (0 - 3)^2 = 9.
- Next jump to heights[1] = 3: (3 - 3)^2 = 0.
Total calories burned = 9 + 0 = 9.
Constraints:
1 <= n == heights.length <= 10^51 <= heights[i] <= 10^5
Solution
Approach: Greedy + Sorting
The order of the jumps matters, so to burn as much as possible we want every jump to cover a large height difference. Sort the heights, then alternate between the highest and the lowest block that have not been used yet: start from the ground and jump to the highest block, then to the lowest, then to the second highest, then the second lowest, and so on.
Concretely, keep two pointers l (lowest unused) and r (highest unused) and the previous height pre = 0. While l < r, add (heights[r] - pre)^2 and (heights[l] - heights[r])^2, set pre = heights[l], and move both pointers inward. When the pointers meet, one block is left in the middle: add (heights[r] - pre)^2 for it.
Complexity: time O(n log n) for the sort, space O(1) extra (besides the sort), where n is the number of blocks. The total can reach about 10^15, so use 64-bit integers.
class Solution:
def maxCaloriesBurnt(self, heights: List[int]) -> int:
heights.sort()
pre = 0
l, r = 0, len(heights) - 1
ans = 0
while l < r:
ans += (heights[r] - pre) ** 2
ans += (heights[l] - heights[r]) ** 2
pre = heights[l]
l, r = l + 1, r - 1
ans += (heights[r] - pre) ** 2
return ans