TikTok VO Coding Interview: Repeatedly Merge the Largest Two Numbers to Find the GCD

15 Views
No Comments

Find the maximum common divisor by repeatedly merging the largest two numbers.

Question description

Given a list A containing n numbers, repeatedly select the two adjacent numbers with the largest sum in the list, merge them into one number, and continue this process until only one number remains. Output that number.

Example

  • [2, 4, 6, 12]
  • [2, 2, 6]
  • [2, 2]
  • [2]

output: 2

math.gcd(A, B)

This problem asks you to repeatedly merge the adjacent pair with the largest sum until only one value remains, then return the final result. The example shows the sequence shrinking from `[2, 4, 6, 12]` to `2`. A good solution needs to track neighboring sums efficiently and update them after each merge, often using a heap or linked structure depending on the exact rules. The visible `gcd` hint suggests there may also be an underlying mathematical property to exploit.

END
 0