Program to find minimum amplitude after deleting K elements in Python

Given a list of numbers and a value k, we need to find the minimum amplitude (difference between maximum and minimum) after removing k elements from the list.

So, if the input is like nums = [4, 10, 3, 2, 8, 9] and k = 3, then the output will be 2. If we remove 10, 8, and 9, the remaining elements are [4, 3, 2], where maximum is 4 and minimum is 2, giving us an amplitude of 2.

Algorithm

To solve this problem, we will follow these steps ?

  • Sort the list nums to arrange elements in ascending order

  • Calculate p = size of nums - k (remaining elements after deletion)

  • Initialize minimum amplitude with the difference between last and first elements

  • Use a sliding window of size p to find the minimum amplitude among all possible subarrays

  • Return the minimum amplitude found

Example

Let's implement the solution to find minimum amplitude ?

def solve(nums, k):
    nums = sorted(nums)
    p = len(nums) - k
    min_amplitude = nums[-1] - nums[0]
    
    for i in range(0, len(nums) - p + 1):
        current_amplitude = nums[i + p - 1] - nums[i]
        if current_amplitude < min_amplitude:
            min_amplitude = current_amplitude
    
    return min_amplitude

nums = [10, 4, 3, 2, 9, 8]
k = 3
result = solve(nums, k)
print(f"Minimum amplitude after removing {k} elements: {result}")
Minimum amplitude after removing 3 elements: 2

How It Works

The algorithm works by sorting the array first, then using a sliding window approach. After sorting [10, 4, 3, 2, 9, 8] becomes [2, 3, 4, 8, 9, 10]. With k=3, we need to keep p=3 elements.

We check all possible subarrays of length 3:

  • [2, 3, 4] ? amplitude = 4 - 2 = 2

  • [3, 4, 8] ? amplitude = 8 - 3 = 5

  • [4, 8, 9] ? amplitude = 9 - 4 = 5

  • [8, 9, 10] ? amplitude = 10 - 8 = 2

The minimum amplitude is 2, achieved by keeping either [2, 3, 4] or [8, 9, 10].

Alternative Implementation

Here's a more concise version using Python's built-in functions ?

def solve_concise(nums, k):
    nums.sort()
    p = len(nums) - k
    return min(nums[i + p - 1] - nums[i] for i in range(len(nums) - p + 1))

nums = [4, 10, 3, 2, 8, 9]
k = 3
result = solve_concise(nums, k)
print(f"Result: {result}")
Result: 2

Conclusion

The key insight is to sort the array first, then use a sliding window to find the minimum amplitude among all possible subarrays of size (n-k). This approach ensures we find the optimal solution with O(n log n) time complexity.

Updated on: 2026-03-26T15:51:34+05:30

591 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements