703189. Find minimum adjustment cost of an array
Easy
Find Minimum Adjustment Cost of an Array
Slug: find-minimum-adjustment-cost-of-an-array4628
Difficulty: Easy
Id: 703189
Topic Tags: Arrays, Dynamic Programming, Data Structures, Algorithms
Company Tags: None
Summary
Find the minimum adjustment cost to make all elements in an array equal. The adjustment cost is calculated as the sum of absolute differences between each element and a common target value.
Detailed Explanation
The problem can be approached by using dynamic programming. First, find the median of the array, which will be the target value for the adjustment cost calculation. Then, iterate through the array to calculate the total adjustment cost. For each element in the array, subtract the target value and add the absolute difference to the total adjustment cost.
Here's a step-by-step breakdown:
- Find the median of the array, which can be done by sorting the array and selecting the middle value.
- Calculate the total adjustment cost by iterating through the array. For each element:
- Subtract the target value from the element.
- Add the absolute difference to the total adjustment cost.
Time complexity: O(n log n) due to the sorting step. Space complexity: O(1) as no additional space is used.
Optimized Solutions
Java
public class Main {
public static int minAdjustmentCost(int[] arr) {
Arrays.sort(arr);
int median = arr[arr.length / 2];
int totalCost = 0;
for (int num : arr) {
totalCost += Math.abs(num - median);
}
return totalCost;
}
public static void main(String[] args) {
int[] arr = {1, 3, 5};
System.out.println(minAdjustmentCost(arr));
}
}