← Questions

Order jumps between blocks to burn the most calories

0
AmazonCodingLast asked Sep 2025

A coding interview question asked in Amazon's online assessment, last asked Sep 2025. It tests greedy, sorting and two pointers.

A jumping workout: you stand on the ground (height 0) next to n blocks with the given heights. You must jump onto every block exactly once, in any order, and after the first jump you may only jump between blocks, never back to the ground. A jump from height x to height y burns (x - y)^2 calories, and the first jump from the ground counts too. Return the most calories you can burn.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • max_calories(height: list[int]) -> int

Example

max_calories([5, 2, 5])     ->  43    # ground -> 5 -> 2 -> 5: 25 + 9 + 9
max_calories([1, 3, 7])     ->  89    # ground -> 7 -> 1 -> 3: 49 + 36 + 4
max_calories([2, 8, 4, 6])  ->  120   # ground -> 8 -> 2 -> 6 -> 4: 64 + 36 + 16 + 4
max_calories([])            ->  0

Constraints

  • 0 <= n <= 10^5; 0 <= height[i] <= 10^9, so the total needs 64-bit integers.

Clarifying questions

  • Does the first jump from the ground count? (Yes.)
  • Can heights repeat? Can a block have height 0?
  • Must you end anywhere in particular? (No.)

What a strong answer covers

  • The greedy order: sort, then alternate tallest remaining, shortest remaining, tallest remaining, and so on, starting with the tallest (so the jump from 0 is as large as possible). O(n log n).
  • An argument for it: expanding the total, each height appears in squared terms and in cross terms -2·x·y between neighbours, so the order should put tall blocks next to short ones; an exchange argument shows swapping out of the zigzag never helps.
  • Checking the greedy against an exact search for small n (a bitmask DP over subsets, dp[mask][last], or trying every order), which is the fallback if you cannot justify the greedy.
  • Ties, n = 0 and n = 1, and overflow.

Follow-ups

  • You must end on the ground as well. What changes?
  • The cost is |x - y| instead of the square. Is the same order still best?
  • Return the order, not just the total.

Where it's asked

  • Amazon · Online assessment · Last asked Sep 2025Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant

What it tests

greedy · sorting · two pointers

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding