# Program to find array of length k from given array whose unfairness is minimum in python

PythonServer Side ProgrammingProgramming

Suppose we have an array A and another value k. We have to form an array arr whose size is k bu taking elements from A and minimize the unfairness. Here the unfairness is calculated by this formula −

(𝑚𝑎𝑥𝑖𝑚𝑢𝑚 𝑜𝑓 𝑎𝑟𝑟) − (𝑚𝑖𝑛𝑖𝑚𝑢𝑚 𝑜𝑓 𝑎𝑟𝑟)

So, if the input is like A = [25, 120, 350, 150, 2500, 25, 35] and k = 3, then the output will be 10, because we can take elements [25, 25, 35] so max(arr) = 35 and min(arr) = 25. So their difference is 10.

To solve this, we will follow these steps −

• i:= 0
• sort the list A
• n := size of A
• m:= A[n-1]
• x:= 0, y:= 0
• while i < n-k, do
• if A[i+k-1] - A[i] < m, then
• m := A[i+k-1] - A[i]
• i := i + 1
• return m

## Example

Let us see the following implementation to get better understanding −

def solve(A, k):
i=0
A.sort()
n = len(A)
m=A[n-1]
x=0
y=0
while i<n-k:
if(A[i+k-1]-A[i]<m):
m=A[i+k-1]-A[i]
i+=1
return m

A = [25, 120, 350, 150, 2500, 25, 35]
k = 3
print(solve(A, k))

## Input

[25, 120, 350, 150, 2500, 25, 35]

## Output

10
Updated on 11-Oct-2021 07:51:07