702831. Minimum Steps
Minimum Steps
Summary
Given an array of integers, find the minimum number of steps required to make all elements equal. In each step, you can either increment or decrement one element by 1.
Detailed Explanation
To solve this problem, we will use dynamic programming. The idea is to maintain a state where dp[i] represents the minimum number of steps required to make all elements from index 0 to i equal. We initialize dp[0] = 0, as it takes 0 steps to make all elements equal when there's only one element.
We then iterate over the array, and for each element at index i, we calculate the minimum number of steps required to make all elements from index 0 to i equal. We consider two cases:
- If the current element is equal to the median of the elements from index 0 to
i-1, then we can leave this element as it is and recursively calculate the minimum number of steps for the remaining elements. - Otherwise, we need to adjust the current element to match the median. We do this by subtracting or adding the difference between the current element and the median from all elements from index 0 to
i-1. This requires additional steps.
We update dp[i] with the minimum of these two cases. Finally, we return dp[n-1], where n is the length of the array, as this represents the minimum number of steps required to make all elements equal.
Here's a step-by-step breakdown:
dp[0] = 0
for i from 1 to n-1:
if arr[i] == median(arr[0..i-1]):
dp[i] = dp[i-1]
else:
diff = abs(arr[i] - median(arr[0..i-1]))
dp[i] = min(dp[i-1], dp[i-1] + 2*diff)
return dp[n-1]
Time complexity: O(n log n) due to the sorting operation Space complexity: O(n)
Optimized Solutions
Java
public int minSteps(int[] arr) {
Arrays.sort(arr);
int median = arr[arr.length / 2];
int steps = 0;
for (int i : arr) {
steps += Math.abs(i - median);
}
return steps;
}