The goal of this program is to make all numbers in an array the same. You have to increment all values in the array except for one each time. Then the program will print out the minimum number of steps it would take to make all the numbers the same. I have what I believe is a working solution I just want to make it more efficient, does any one have any ideas? In the following code the user enters the initial values for the numbers into the array and then calculates the amount of steps required
public static void main(String[] args) throws NumberFormatException, IOException
{
counter=0;
size=sc.nextInt();
input= new int[size];
for(int k=0; k<size; k++)
{
input[k]=sc.nextInt();
}
while(!isAllEqual(input))
{
Arrays.sort(input);
for(int k=0; k<input.length-1; k++)
{
input[k]++;
}
counter++;
}
pw.println(counter);
public static boolean isAllEqual(int[] a){
for(int i=1; i<a.length; i++){
if(a[0] != a[i]){
return false;
}
}
return true;
}
MAJOR EDIT AS I MISREAD THE QUESTION
Scan through the list just once to find the minimum value in the list and the total of adding all the values together.
Once you have these two values, the number of required increments is:
[total of all the values] - [number of items in list] * [minimum value]
In code:
This works because (as Matti Virkkunen pointed out) the number of decrements for each item is
(a[i] - min )
so for the entire list it issum(a[i]-min)
which we can expand tosum(a[i]-(length*min)
.The corresponding increments would be at each step to increment everything except the right most item which is equal to the maximum. For example:
Initial state = (0,1,1,1) 1. increment everything except a[3] --> (1,2,2,1) 2. increment everything except a[2] --> (2,3,2,2) 3. increment everything except a[1] --> (3,3,3,3) : solution in three steps = (1+1+1) - (4 * 0)
and again, initial state of (1,2,3,3)
It might be easier to wrap your head around this if you change the step into something simpler. If we're only talking about equality between the values (i.e. relative, not absolute values), incrementing and decrementing all of the values at once makes no difference. If we change our step to "increment all but one, then decrement every value by one", we can see that incrementing all but one is equivalent to decrementing a single value.
Can you figure out the number of steps to make the values equal if the step is "decrement one value"? It should involve looping through the array two times at max, and no sorting.