Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for 2616. Minimize the Maximum Difference of Pairs
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on

2616. Minimize the Maximum Difference of Pairs

2616. Minimize the Maximum Difference of Pairs

Difficulty: Medium

Topics:Array,Binary Search,Greedy

You are given a0-indexed integer arraynums and an integerp. Findp pairs of indices ofnums such that themaximum difference amongst all the pairs isminimized. Also, ensure no index appears more than once amongst thep pairs.

Note that for a pair of elements at the indexi andj, the difference of this pair is|nums[i] - nums[j]|, where|x| represents theabsolute value ofx.

Return theminimum maximum difference among allp pairs. We define the maximum of an empty set to be zero.

Example 1:

  • Input: nums = [10,1,2,7,1,3], p = 2
  • Output: 1
  • Explanation:
    • The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5.
    • The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1.

Example 2:

  • Input: nums = [4,2,1,2], p = 1
  • Output: 0
  • Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain.

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109
  • 0 <= p <= (nums.length)/2

Hint:

  1. Can we use dynamic programming here?
  2. To minimize the answer, the array should be sorted first.
  3. The recurrence relation is fn(i, x) = min(fn(i+1, x), max(abs(nums[i]-nums[i+1]), fn(i+2, p-1)), and fn(0,p) gives the desired answer.

Solution:

We need to minimize the maximum difference amongp pairs of indices in an array such that no index appears more than once. The solution involves sorting the array and using binary search to efficiently determine the smallest possible maximum difference.

Approach

  1. Problem Analysis: The problem requires selectingp pairs of indices from the array such that the maximum absolute difference among all pairs is minimized. Each index can be used at most once. The key insight is that sorting the array allows us to consider adjacent elements for forming pairs with the smallest possible differences, which helps in minimizing the maximum difference.

  2. Binary Search Setup: We use binary search on the possible range of maximum differences (from 0 to the difference between the largest and smallest elements in the sorted array). The goal is to find the smallest valuemid such that at leastp pairs can be formed where each pair's difference is at mostmid.

  3. Greedy Pair Formation: For each candidatemid during the binary search, we traverse the sorted array and greedily form pairs. If the difference between the current element and the next element is withinmid, we form a pair and skip the next element. This greedy approach ensures we maximize the number of pairs formed, which is crucial for checking the feasibility ofmid.

  4. Binary Search Execution: The binary search narrows down the smallestmid where the greedy method forms at leastp pairs. If amid value allows formingp pairs, we search for a smaller value; otherwise, we search for a larger value.

Let's implement this solution in PHP:2616. Minimize the Maximum Difference of Pairs

<?php/** * @param Integer[] $nums * @param Integer $p * @return Integer */functionminimizeMax($nums,$p){........./**     * go to ./solution.php     */}/** * @param $nums * @param $mid * @param $p * @return bool */functioncanFormPairs($nums,$mid,$p){........./**     * go to ./solution.php     */}// Test cases$nums1=array(10,1,2,7,1,3);$p1=2;echo"Output 1: ".minimizeMax($nums1,$p1)."\n";// Output: 1$nums2=array(4,2,1,2);$p2=1;echo"Output 2: ".minimizeMax($nums2,$p2)."\n";// Output: 0?>
Enter fullscreen modeExit fullscreen mode

Explanation:

  1. Initial Check: Ifp is zero, the result is zero since no pairs are needed.
  2. Sorting: The array is sorted to facilitate adjacent element pairing, which helps in minimizing differences.
  3. Binary Search: The search space is between 0 and the difference between the largest and smallest elements. For each midpointmid, we check if it's possible to form at leastp pairs where each pair's difference is at mostmid.
  4. Greedy Validation: ThecanFormPairs function traverses the sorted array, forming pairs whenever adjacent elements meet the difference constraint. It skips the next element after forming a pair to avoid reuse. Ifp pairs are formed, it returns early.
  5. Binary Search Adjustment: Based on whethermid allows forming enough pairs, the search space is adjusted. If feasible, we search for a smallermid; otherwise, we search larger values. The loop exits when the smallest feasiblemid is found.

This approach efficiently narrows down the solution using binary search and validates candidates with a linear pass through the array, ensuring optimal performance.

Contact Links

If you found this series helpful, please consider giving therepository a star on GitHub or sharing the post on your favorite social networks 😍.Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a Technical Lead with holistic knowledge of software development and design. I am also experienced in coordinating with stakeholders
  • Location
    2 NO MUSLIM NAGAR, MATUAIL, TUSHARDHARA, DEMRA - 1362, DHAKA, BANGLADESH
  • Education
    AHSANULLAH UNIVERSITY OF SCIENCE AND TECHNOLOGY
  • Pronouns
    he/him
  • Work
    TECH LEAD at MT TECHNOLOGIES
  • Joined

More fromMD ARIFUL HAQUE

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp