Program to find minimum amplitude after deleting KLength sublist in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums and a value k. First we shall remove a sublist of size k, then find the minimum of (maximum of nums - minimum of nums).

So, if the input is like nums = [2, 3, 10, 9, 8, 4] k = 3, then the output will be 2, If we remove [10, 9, 8] we get [2, 3, 4] and 4 - 2 = 2

To solve this, we will follow these steps −

  • N := size of nums

  • copy nums into lmin and lmax

  • also copy nums into rmin and rmax

  • for i in range 1 to N - 1, do

    • lmin[i] := minimum of lmin[i] and lmin[i - 1]

    • lmax[i] := maximum of lmax[i] and lmax[i - 1]

  • for i in range N - 2 to 0, decrease by 1, do

    • rmin[i] := minimum of rmin[i] and rmin[i + 1]

    • rmax[i] := maximum of rmax[i] and rmax[i + 1]

  • ans := minimum of (rmax[k] - rmin[k]), (lmax[complement of k] - lmin[complement of k])

  • for i in range 0 to N - k - 2, do

    • cand := (maximum of lmax[i] and rmax[i + k + 1]) - (minimum of lmin[i] and rmin[i + k + 1])

    • ans := minimum of ans and cand

  • return ans

Example

Let us see the following implementation to get better understanding

def solve(nums, k):
   N = len(nums)
   lmin, lmax = nums[:], nums[:]
   rmin, rmax = nums[:], nums[:]
   for i in range(1, N):
      lmin[i] = min(lmin[i], lmin[i - 1])
      lmax[i] = max(lmax[i], lmax[i - 1])
   for i in range(N - 2, -1, -1):
      rmin[i] = min(rmin[i], rmin[i + 1])
      rmax[i] = max(rmax[i], rmax[i + 1])

   ans = min(rmax[k] - rmin[k], lmax[~k] - lmin[~k])
   for i in range(N - k - 1):
      cand = max(lmax[i], rmax[i + k + 1]) - min(lmin[i], rmin[i + k + 1])
      ans = min(ans, cand)

   return ans

nums = [2, 3, 10, 9, 8, 4]
k = 3
print(solve(nums, k))

Input

[2, 3, 10, 9, 8, 4], 3

Output

2
raja
Published on 12-Oct-2021 11:15:05
Advertisements