Minimize difference between array values

Chaitra Rai
2 min readOct 18, 2021

You are given an integer array nums and an integer k. The score of nums is the difference between the maximum and minimum elements in nums. Return the minimum score of nums after changing the values at each index. (Question 1, Question 2)

  • The first question is to add and subtract value k to the minimum and maximum values of the array respectively and hence reduce the score
  • Hence considering this above perspective all we have to do is reduce the window between the maximum and minimum value; one has to level up the minimum value with given k and level down the maximum value with given k
public int smallestRangeI(int[] nums, int k) {
Arrays.sort(nums);
int score=Integer.MAX_VALUE;
int min=nums[0];
int max=nums[nums.length-1];
score=Math.min(score,(max-k)-(min+k));
return score <= 0 ? 0 : score;

}
  • The time complexity of this solution would be O(N log N) considering the sorting included
  • The second question lies on similar grounds but here the catch is to operate with k on every single value in the array
  • one would have to reduce and find the least or minimum score and reduce the window of difference
  • we could iterate through the array and for each value at index and index+1, find out if the value could be a potential maximum or minimum value by comparing with the existing minimum and maximum value
public int smallestRangeII(int[] nums, int k) {
int n=nums.length;
Arrays.sort(nums);
int score=nums[n-1]-nums[0];
for(int i=0;i<n-1;i++){
int a=nums[i];
int b=nums[i+1];
int max=Math.max(nums[n-1]-k,a+k);
int min=Math.min(nums[0]+k,b-k);
score=Math.min(score,max-min);
}
return score;
}
  • The time complexity of the problem is O(N log N)

--

--

Chaitra Rai

Intimidated developer trying to find her way into technology dominant world