Choose a Shared Array Value with Minimum Weighted Unit Cost

Quick Overview

Make all array values equal with minimum total cost when each entry has its own fixed cost per unit increase or decrease.

Choose a Shared Array Value with Minimum Weighted Unit Cost

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

### Problem Changing `nums[i]` by one in either direction costs `cost[i]`. You may make any number of such changes. Return the minimum total cost needed to make every entry of `nums` equal. Both input arrays contain positive integers. ```cpp class Solution { public: long long minCost(vector<int>& nums, vector<int>& cost); }; ``` ### Examples **Example 1:** ```text Input: nums = [1,4], cost = [2,1] Output: 3 Explanation: Move4 down to 1 for 3 units at unit cost 1; targeting4 would cost 6. ``` **Example 2:** ```text Input: nums = [6,6], cost = [4,9] Output: 0 Explanation: The values already agree. ``` ### Constraints - The arrays have equal length `n`, with `1 <= n <= 100000`. - `1 <= nums[i], cost[i] <= 1000000`. - The answer is guaranteed not to exceed `2^53 - 1`. ### Clarifying Questions - Does an entry's unit cost change as its value changes? No. - May changes increase or decrease a value? Either direction is allowed. - Must the common target be returned? No; return only the minimum total cost. - Are zero operations allowed? Yes, including when entries already agree. ```hint Check the boundary Compare equal-size changes to entries whose unit costs differ. ```

Overview: Make all array values equal with minimum total cost when each entry has its own fixed cost per unit increase or decrease.

Amazon logo
Amazon
Source window: 0–3 months · as of Oct 21, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Changing nums[i] by one in either direction costs cost[i]. You may make any number of such changes. Return the minimum total cost needed to make every entry of nums equal. Both input arrays contain positive integers.

class Solution {
public:
    long long minCost(vector<int>& nums, vector<int>& cost);
};

Examples

Example 1:

Input: nums = [1,4], cost = [2,1]
Output: 3
Explanation: Move4 down to 1 for 3 units at unit cost 1; targeting4 would cost 6.

Example 2:

Input: nums = [6,6], cost = [4,9]
Output: 0
Explanation: The values already agree.

Constraints

  • The arrays have equal length n , with 1 <= n <= 100000 .
  • 1 <= nums[i], cost[i] <= 1000000 .
  • The answer is guaranteed not to exceed 2^53 - 1 .

Clarifying Questions Guidance

  • Does an entry's unit cost change as its value changes? No.
  • May changes increase or decrease a value? Either direction is allowed.
  • Must the common target be returned? No; return only the minimum total cost.
  • Are zero operations allowed? Yes, including when entries already agree.