# Solution For Minimize Deviation In Array

Problem Statement:

You are given an array nums of n positive integers.
You can perform two types of operations on any element of the array any number of times:
If the element is even, divide it by 2.
For example, if the array is [1,2,3,4], you can perform the following operations:
1. Divide the second element by 2 twice and get [1,1,3,4].
2. Divide the third element by 2 and get [1,2,1,4].

The deviation of the array is the maximum difference between any two elements in the array.
Return the minimum deviation the array can have after performing some number of operations.

Example:
Input: nums = [1,2,3,4] Output: 1
Explanation:
You can transform the array to [1,1,3,4], then the deviation will be 4-1 = 3, which is the minimum possible.

Approach:

To solve this problem, we can use a greedy approach. We first convert all odd numbers in the array to even numbers by multiplying them by 2. Then, we repeatedly perform the following steps until we cannot perform any further operations:

1. Find the maximum number in the array.
2. Divide the maximum number by 2.
3. If the divided number is even, replace the maximum number with the divided number; otherwise, we add the original maximum number to a min heap and replace the maximum number with the minimum element in the heap.

Finally, we return the difference between the maximum and the minimum element in the array, which is the deviation we need to minimize.

Solution:

First, we will import the heapq library in Python to implement the min heap. Then, we will create an empty min heap and transform all odd numbers in the array to even numbers by multiplying them by 2.

import heapq

class Solution:
def minimumDeviation(self, nums: List[int]) -> int:
min_heap = [] for i in range(len(nums)):
if nums[i] % 2 == 1:
nums[i] *= 2

Now, we will perform the steps mentioned above until we cannot perform any further operations. To find the maximum number in the array, we can simply use the max() function in Python. Then, we can divide the maximum number by 2 and check if the divided number is even. If it is, we can replace the maximum number with the divided number, and continue with the next iteration. Otherwise, we add the original maximum number to the heap and replace the maximum number with the minimum element in the heap using the heapreplace() function. We also keep track of the minimum deviation we have found so far.

``````    ...
max_num = max(nums)
min_deviation = float('inf')
while True:
min_num = heapq.heappop(nums)
min_deviation = min(min_deviation, max_num - min_num)
if max_num % 2 == 1:
heapq.heappush(min_heap, -max_num)
max_num = max(max_num//2, min_heap)
heapq.heapreplace(min_heap, -max_num)
else:
max_num //= 2
if min_heap and max_num <= -min_heap:
break
return min_deviation
``````

Full Code:

import heapq

class Solution:
def minimumDeviation(self, nums: List[int]) -> int:
min_heap = [] for i in range(len(nums)):
if nums[i] % 2 == 1:
nums[i] *= 2
max_num = max(nums)
min_deviation = float(‘inf’)
while True:
min_num = heapq.heappop(nums)
min_deviation = min(min_deviation, max_num – min_num)
if max_num % 2 == 1:
heapq.heappush(min_heap, -max_num)
max_num = max(max_num//2, min_heap)
heapq.heapreplace(min_heap, -max_num)
else:
max_num //= 2
if min_heap and max_num <= -min_heap:
break
return min_deviation

## Step by Step Implementation For Minimize Deviation In Array

```class Solution {
public int minDeviation(int[] nums) {
// sort the array
Arrays.sort(nums);

// initialize the minimum deviation to be the difference between the first and last elements in the array
int minDev = nums[nums.length-1] - nums;

// for each element in the array
for (int i = 0; i < nums.length; i++) {
// calculate the difference between that element and the element to its right
int dev = nums[i+1] - nums[i];
// if that difference is less than the current minimum deviation
if (dev < minDev) {
// update the minimum deviation
minDev = dev;
}
}

// return the minimum deviation
return minDev;
}
}```
```Given an array A of n integers, find a permutation of A that minimizes the sum of |A[i] - i| over all 0 <= i < n. If there are multiple answers, return any permutation that minimizes the sum.

def minDeviation(A):

# Sort the given array

A.sort()

# Initialize result

n = len(A)

res = 0

for i in range(n):

# Subtract the ith element from its

# actual position

res += abs(A[i] - i)

return res```
```/**
* @param {number[]} nums
* @return {number}
*/
var minimumDeviation = function(nums) {
// sort the array in ascending order
nums.sort((a, b) => a - b);

// initialize the minimum deviation to be the difference between the first and second elements in the array
let minDeviation = nums - nums;

// iterate through the array starting at the second element
for (let i = 1; i < nums.length; i++) {
// calculate the difference between the current element and the previous element
let diff = nums[i] - nums[i-1];

// if the difference is less than the current minimum deviation, update the minimum deviation
if (diff < minDeviation) {
minDeviation = diff;
}
}

return minDeviation;
};```
```We can use a greedy approach to solve this problem. First, let's sort the array. Then, we can iterate through the array and keep track of the current minimum deviation. At each step, we can update the current minimum deviation by considering the difference between the current element and the previous element.

#include  #include  #include  using namespace std; int main() { vector nums = {4, 10, 15, 24, 26}; // Sort the array sort(nums.begin(), nums.end()); // Initialize the minimum deviation int minDev = nums - nums; // Iterate through the array for (int i = 1; i < nums.size(); i++) { // Update the minimum deviation minDev = min(minDev, nums[i] - nums[i-1]); } // Print the minimum deviation cout << minDev << endl; return 0; }```
```Given an array A of n integers, find a subset of A with minimum sum of absolute deviations from the subset's mean.

For example, given A = [1,2,3], the subset [1,2] has a sum of abs(1-2) + abs(2-2) = 1 and abs(1-2.5) + abs(2-2.5) = 0.5, so it has minimum sum of absolute deviations.

We can solve this problem in linear time using dynamic programming. Let dp[i][j] be the minimum sum of absolute deviations for the subset A[i..j]. We can compute dp[i][j] using the following recurrence:

dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + sum(A[i..j])), for i <= k < j

The intuition behind this recurrence is as follows. If we have already computed the minimum sum of absolute deviations for the subsets A[i..k] and A[k+1..j], then we can compute the minimum sum of absolute deviations for the subset A[i..j] by considering all possible partitions of A[i..j] into two subsets A[i..k] and A[k+1..j].

We can compute dp[i][j] in O(n^3) time using the above recurrence. However, we can improve the running time to O(n^2) by using a more efficient algorithm to compute the sums of the subsets A[i..j].

The following is the C# code for the solution:

public static int MinDeviation(int[] A) { int n = A.Length; int[,] dp = new int[n, n]; for (int i = 0; i < n; i++) { dp[i, i] = 0; } for (int len = 2; len <= n; len++) { for (int i = 0; i <= n - len; i++) { int j = i + len - 1; dp[i, j] = int.MaxValue; int sum = 0; for (int k = i; k <= j; k++) { sum += A[k]; } for (int k = i; k < j; k++) { dp[i, j] = Math.Min(dp[i, j], dp[i, k] + dp[k + 1, j] + sum); } } } return dp[0, n - 1]; }```

Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]