Problem Summary
You are given an integer array nums and an integer k.
In one operation, you may choose any element and add or subtract any positive integer from it, but the cost of the operation equals the amount you add or subtract.
Your task is to compute the minimum total cost needed so that every element in the array becomes exactly k.
Example
Input:nums = [4, 3, 1, 7]k = 5
Output: 8
Explanation:
To convert the array to [5, 5, 5, 5], the total operations cost is:|4 − 5| + |3 − 5| + |1 − 5| + |7 − 5| = 1 + 2 + 4 + 2 = 9
Constraints
- 1 ≤ nums.length ≤ 10⁵
- 0 ≤ nums[i], k ≤ 10⁹
- Cost of changing x to y is |x − y|
Approach (Simple English)
The problem statement may look complicated, but the idea is extremely simple.
To make each element equal to k, you must move each value nums[i] directly to k.
The cost of moving one value is:
|nums[i] − k|
Since each number is independent, and there is no interaction between array elements, the final total cost is simply:
sum over all i of |nums[i] − k|
Why This Works
For each element, the cheapest way to reach exactly k is to directly move it to k in a single operation.
The cost is exactly the distance to k.
There is no cheaper path because:
- Splitting the movement into many small operations is worse or equal
- Moving past
kand coming back costs more - Combining elements or using other numbers gives no benefit
Thus, the answer must be a simple summation.
Steps
- Initialize totalCost = 0
- Loop through each number in
nums - Add
Math.abs(num − k)to totalCost - Return totalCost
Time complexity: O(n)
Space complexity: O(1)
Java Code (Optimal Solution)
class Solution {
public long minOperations(int[] nums, int k) {
long total = 0;
for (int num : nums) {
total += Math.abs((long) num - k);
}
return total;
}
}
Notes:
- Use
longbecause values may exceedintlimits when summing many differences. - The logic remains O(n), which easily handles max constraints.
Dry Run
Input:nums = [4, 3, 1, 7], k = 5
Compute individually:
- |4 − 5| = 1
- |3 − 5| = 2
- |1 − 5| = 4
- |7 − 5| = 2
Sum = 1 + 2 + 4 + 2 = 9
Return 9.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Edge Cases
- nums already all equal to k → answer is 0
- nums contains very large values →
longhandles it - nums of length 1 → cost is simply |nums[0] − k|
- Mixed values above and below k → absolute value handles both
