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

    Input

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

    Output

    10
    Updated on: 2021-10-11T07:51:07+05:30

    627 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements