I am struggling with this particular problem and am not very sure how to approach it, any idea would really be appreciated.
I have an array of size n, for example, 3
[8, 10, 5]
I want to subtract values from this array until all the indexes become equal, using the smallest amount of subtracted values as possible.
The answer for this particular question would be
8 10 5
8 8 3 Subtract 2 from index 1 and 2
3 3 3 Subtract 5 from index 0 and 1
[3, 3, 3]
Requirements:
Array must not move (no moving indexes)
Only subtracting is allowed
You are only allowed to subtract by TWO indexes that are right NEXT to each other (eg. if I want to decrease index[1], I would have to also decrease index[0] or index[2])
Subtracting multiple indexes must be the same value (eg. subtracting index[1] by 3, I must choose an index right next to index[1] and subtract that by the same amount (3))
Objective: Make all values in the array equal by subtracting as less as possible.
Any help is appreciated, as I have absolutely no idea of how to even start tackling this!
CodePudding user response:
First you find the maximum and the minimum by iterating the array . for eg, in this
array = {8,10,5}
max is 10 and min is 5.
Then you subtract the difference (5) from the maximum and its adjacent and ignoring the value which is in less adjacent.( in this case, neighbours of 10 are 8,5 -> therefore, subtract 5 from 8) ,then
arrays ={3,5,5}
now again iterate the array and find max and min ( 5,3) . Subtract the difference ( 5-3 =2 ) from the max and its adjcent neighbour with more value ( from 3,5 , subtract 2 from 5 ) then your array becomes
arrays ={3,3,3}
CodePudding user response:
Easy solution :
static int equalizeArray(int N, int k, int arr[])
{
long steps=0;
Arrays.sort(arr);
int mid=0;
if(N%2==1){
mid=N/2;
}
else{
mid=N/2-1;
}
for( int i=0;i<N;i ){
if( (Math.abs(arr[i]-arr[mid]))%k!=0){
return -1;
}
}
for( int i=0;i<N;i ){
long diff=Math.abs(arr[i]-arr[mid]);
steps =(diff/k)00000007;
}
return (int)steps00000007;
}
