Minimize Deviation in Array - Problem
Problem: You are given an array
Available Operations:
• If an element is even, you can divide it by 2
• If an element is odd, you can multiply it by 2
The deviation is defined as the maximum difference between any two elements in the array after performing operations.
Example: Given
Goal: Return the minimum possible deviation after performing any number of operations.
nums of n positive integers. Your goal is to minimize the deviation of the array through strategic operations.Available Operations:
• If an element is even, you can divide it by 2
• If an element is odd, you can multiply it by 2
The deviation is defined as the maximum difference between any two elements in the array after performing operations.
Example: Given
[1,2,3,4], you could transform it to [2,1,6,1] by: multiply 1→2, divide 2→1, multiply 3→6, divide 4→2→1. The deviation would be 6-1=5.Goal: Return the minimum possible deviation after performing any number of operations.
Input & Output
example_1.py — Basic Case
$
Input:
nums = [1,2,3,4]
›
Output:
1
💡 Note:
Start with [1,2,3,4]. Double odds: [2,2,6,4]. Then systematically reduce: 6→3, 4→2→1. Final possible arrays include [1,1,3,1] with deviation 3-1=2, or [2,1,3,1] with deviation 3-1=2, or [2,2,3,2] with deviation 3-2=1. The minimum deviation is 1.
example_2.py — All Even Numbers
$
Input:
nums = [4,1,5,20,3]
›
Output:
3
💡 Note:
Double odds: [4,2,10,20,6]. Systematically reduce maximums: 20→10→5, then 10→5, then 6→3. Through optimal reductions, we can achieve arrays like [4,2,5,5,3] with deviation 5-2=3.
example_3.py — Single Element
$
Input:
nums = [2]
›
Output:
0
💡 Note:
With only one element, the deviation is always 0 since max - min = element - element = 0.
Constraints
- n == nums.length
- 1 ≤ n ≤ 105
- 1 ≤ nums[i] ≤ 109
- All elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Heat All Odd Rooms
First, heat up all rooms at odd temperatures (multiply by 2) since they can only be heated once
2
Track Temperatures
Keep track of the hottest room (max heap) and the coldest temperature ever seen
3
Cool Down Systematically
Always cool down the hottest room (if even temperature) and update the temperature range
4
Stop When Optimal
Stop when the hottest room is at an odd temperature (can't cool further)
Key Takeaway
🎯 Key Insight: Always maximize odd numbers first (they can only increase once), then systematically reduce the maximum element while tracking the global minimum. This greedy approach guarantees the optimal solution.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code