
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- C++ Program to find Number Whose XOR Sum with Given Array is a Given Number k
- Minimum Possible value of |ai + aj – k| for given array and k in C++
- Program to find minimum moves to make array complementary in Python
- Program to find number of K-Length sublists whose average is greater or same as target 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 length of lossy Run-Length Encoding in Python
- Program to find minimum operations to make array equal using Python
- Program to find three unique elements from list whose sum is closest to k Python
- Program to find maximum length of k ribbons of same length in Python
- C++ program to find perfect array of size n whose subarray is a good array
- Program to find length of longest sublist whose sum is 0 in Python
- Program to find length longest prefix sequence of a word array in Python
- Find the K-th minimum element from an array concatenated M times in C++
- C++ program to find string with palindrome substring whose length is at most k
- Program to find minimum operations to make the array increasing using Python

Advertisements