Similar Problems

Similar Problems not available

Minimize The Difference Between Target And Chosen Elements - Leetcode Solution

Companies:

LeetCode:  Minimize The Difference Between Target And Chosen Elements Leetcode Solution

Difficulty: Medium

Topics: matrix dynamic-programming array  

Problem Statement:

Given an array nums of n integers and an integer target, find the minimum absolute difference between any two elements of the array such that the absolute difference is less than or equal to target.

Write a function to return the minimum absolute difference.

Examples:

Input: nums = [4,9,3], target = 10 Output: 3 Explanation: Choosing 9 and 3 gives minimum difference of 3.

Input: nums = [2,3,4,7,8,9], target = 5 Output: 0 Explanation: Choosing 4 and 4 or 5 and 7 gives minimum difference of 0.

Solution:

To find the minimum absolute difference between any two elements of the array such that the absolute difference is less than or equal to target, we can sort the given array. Once we have sorted the array, we can use a sliding window technique to find the subarray whose absolute difference is less than or equal to target. We need to keep track of the minimum absolute difference between any two elements of the subarray to return the answer.

Steps:

  1. Sort the input array nums.
  2. Initialize the minimum absolute difference as infinity.
  3. Initialize two pointers, left and right, as 0 and 1 respectively.
  4. Move the right pointer until the absolute difference between nums[right] and nums[left] is less than or equal to target.
  5. After moving the right pointer, update the minimum absolute difference if the absolute difference between nums[right] and nums[left] is less than the current minimum absolute difference.
  6. Once we have found a subarray where the absolute difference between any two elements is less than or equal to target, we move the left pointer until the absolute difference between nums[right] and nums[left] is greater than target.
  7. Repeat steps 4-6 until the right pointer reaches the end of the array.
  8. Return the minimum absolute difference.

Here is the Python code implementing the above approach:

def minimizeTheDifference(nums, target): nums.sort() left, right = 0, 1 diff = float('inf') while right < len(nums): while right < len(nums) and abs(nums[right] - nums[left]) <= target: diff = min(diff, abs(nums[right] - nums[left])) right += 1 while left < right and abs(nums[right] - nums[left]) > target: left += 1 return diff

test the function

print(minimizeTheDifference([4,9,3], 10)) # output: 3 print(minimizeTheDifference([2,3,4,7,8,9], 5)) # output: 0

The time complexity of this approach is O(nlogn) due to sorting the input array and the space complexity is O(1) as we are not using any extra space.

Minimize The Difference Between Target And Chosen Elements Solution Code

1