Data Structures & AlgorithmsVery hardCodeforces Div2 C · TCS NQT

The numbers [1, 6, 3, 8, 4] can be arranged in any order in a row. Maximise the sum of absolute differences between neighbouring numbers in the row. What is the largest possible sum?

  1. A. 18
  2. B. 16
  3. C. 21
  4. D. 19

Correct answer: D. 19

Alternate the smallest and largest values (low, high, low, high, ...), which makes each adjacent gap as large as possible. Sorting the numbers in order gives the smallest total, and the greedy zigzag reaches the maximum when built carefully.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic