Skip to content
Advertisement

Minimize the maximum difference

I’m trying to solve this Problem from GFG with following approach:

JavaScript

But i’m unable to pass the testcases:

JavaScript

I’m unable to figure out fault in my logic or code. Could some suggest corrections or better approach?

Advertisement

Answer

I’m unable to figure out fault in my logic or code.

As per your current logic, you decide to add or subtract k just based on the current element. But it might not yield the min diff overall. For example, for 5 you decided to add k and it resulted in the range (5,11) for the whole set. Rather if you have subtracted it would have yielded (1,6).


Could some suggest corrections or better approach?

Approach:

  • Sort the array
  • Lets handle the trivial case, if k > (max - min) then directly return max - min. Since adding k to min and subtracting k from max will yield a larger difference. (To be precise, 2 * k + (max - min))
  • In all other cases, we will add k to min element and subtract k from max element. There should exist an index in the array, where we switch from adding k to subtracting k. The below diagram shows the switch index: enter image description here

(Note: In the diagram, Bcan be less than D and also A can be greater than C)

  • Now we iterate over the array and at each index, if it was the switch index we determine the range.
    • From the diagram, we can calculate the range as below
      • if A < C then the range will start with A or else with C
      • Similarly if B > D then the range will end with B or else with D
  • The min range across all index gives the result

Updated Code:

JavaScript

Explanation:

  • In the for loop, we determine the switch index range for each element as follows
    • Start: From the diagram minimum of A and C. Here A is arr[0] + k and C will be next element - k i.e,. arr[ i + 1 ] - k
    • End: Maximum of B and D. B is current element + k, i.e., arr[i] + k and D will be arr[-1] - k
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement