Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Optimize Array Pairing Cost

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Optimize Array Pairing Cost. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

You are given an integer array nums. In one operation, you may choose any two elements, remove them, and pay a cost equal to the absolute difference of the two values. Continue until no more pairs can be formed. Return the minimum possible total cost.

Implement min_pair_cost(nums) and assume nums may contain duplicates and negative values. If the array has an odd length, one element will remain unpaired and contributes no cost.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • Duplicate values are allowed
  • The array may have odd or even length

Function Signature

def min_pair_cost(nums):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output