Minimum Cost to Make Array Equal

HardMathmath

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given two arrays nums and cost of the same length n. You may increase or decrease any nums[i] by 1 as many times as you like; each such unit change to index i costs cost[i]. Return the **minimum total cost** to make all elements of nums equal to a single common value. The answer can exceed 32 bits, so return a 64-bit integer. Aim for O(n log n).

Examples

Input: nums = [4,1,7], cost = [1,5,2]
Output: 15
Make everything 1: index 0 costs 3*1, index 2 costs 6*2, total 15. Target 4 would cost 21 and target 7 would cost 33.
Input: nums = [6,6,6], cost = [3,9,1]
Output: 0
All elements are already equal.

Constraints

  • `1 <= n <= 10^5`
  • `nums.length == cost.length`
  • `1 <= nums[i], cost[i] <= 10^6`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More math problems