Program to find minimum difference between largest and smallest value in three moves using Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called nums. We can change one element from this array to any value in one move. We have to find the minimum difference between the largest and smallest value of nums after preforming at most 3 moves.

So, if the input is like nums = [3,7,2,12,16], then the output will be 1 because we can make given array to [1,1,0,1,1], so the maximum is 1 and minimum is 0, so the difference is 1.

To solve this, we will follow these steps −

  • if size of nums <= 4, then

    • return 0

  • sort the list nums

  • ans := infinity

  • for i in range 0 to 3, do

    • mi := nums[i]

    • ma := nums[length of nums -(3-i+1)]

    • ans := minimum of ma-mi and ans

  • return ans

Let us see the following implementation to get better understanding −


 Live Demo

def solve(nums):
   if len(nums) <= 4:
      return 0
   ans = float("inf")
   for i in range(4):
      mi = nums[i]
      ma = nums[-(3-i+1)]
      ans = min(ma-mi,ans)
   return ans
nums = [3,7,2,12,16]




Published on 28-May-2021 12:31:38