Minimize Deviation in Array

Hard

Description

You are given an array nums of n positive integers. You can perform two types of operations: if element is even, divide by 2; if element is odd, multiply by 2. Return the minimum difference between the maximum and minimum element after performing operations.

Examples

Input:nums = [1,2,3,4]
Output:1
Explanation:

Start with [6, 10, 15]. Odd numbers can double and even numbers can halve. Through optimal operations, the array reaches [5, 6, 8] (or equivalent) with minimum deviation of 7.

Input:nums = [6, 10, 15]
Output:1
Explanation:

Start with [7, 8]. Multiplying 7 by 2 gives [14, 8], then dividing both until optimal yields [7, 8] with deviation 1. The minimum achievable deviation is 1.

Input:nums = [7, 8]
Output:0
Explanation:

Start with [7, 8]. Multiply 7 by 2: [14, 8]. Divide 8 by 2: [14, 4]. The deviation is 10. Alternatively: [7, 8] -> [7, 4] gives deviation 3. Further: [14, 8] -> [7, 8] gives deviation 1, the minimum achievable.

Constraints

  • n == nums.length
  • 2 ≤ n ≤ 5 * 10^4

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!