- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

- if A[i+k-1] - A[i] < m, then
- 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

- Related Questions & Answers
- C++ Program to find Number Whose XOR Sum with Given Array is a Given Number k
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Program to find length of longest sublist whose sum is 0 in Python
- C++ program to find string with palindrome substring whose length is at most k
- Program to find minimum length of lossy Run-Length Encoding in Python
- Program to find maximum length of k ribbons of same length in Python
- Program to find three unique elements from list whose sum is closest to k Python
- C++ program to find perfect array of size n whose subarray is a good array
- Find the Minimum Number of Fibonacci Numbers Whose Sum Is K in C++
- Program to find product of few numbers whose sum is given in Python
- Program to find number of sublists whose sum is given target in python
- Program to find length of longest valid parenthesis from given string in Python
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to find minimum length of first split of an array with smaller elements than other list in Python
- Program to find minimum number of subsequence whose concatenation is same as target in python

Advertisements