Untitled
unknown
plain_text
a year ago
1.4 kB
7
Indexable
import java.util.Arrays;
public class MinCostEqualArray {
public static int minCost(int[] arr) {
int n = arr.length;
long[] prefixSums = new long[n + 1];
// Calculate prefix sums
for (int i = 0; i < n; i++) {
prefixSums[i + 1] = prefixSums[i] + arr[i];
}
// Initialize variables for minimum cost and target value
long minCost = Long.MAX_VALUE;
int targetValue = 0;
// Iterate over potential target values
for (int target = Arrays.stream(arr).min().getAsInt(); target <= Arrays.stream(arr).max().getAsInt(); target++) {
long currentCost = 0;
// Calculate cost for current target value
for (int i = 0; i < n; i++) {
long diff = Math.abs((long)target * (i + 1) - prefixSums[i + 1]);
currentCost += diff;
}
// Update minimum cost if current cost is lower
if (currentCost < minCost) {
minCost = currentCost;
targetValue = target;
}
}
return (int)minCost;
}
public static void main(String[] args) {
int[] arr = {1, 4, 2, 1};
System.out.println(minCost(arr)); // Expected output based on problem statement
}
}
Editor is loading...
Leave a Comment