educative.io

I don't understand Solution #2 for Max/Min Form of a sorted list

Could you please explain in plain English why the following operations were applied to each each element (either in even or odd positions)? As “line 13” shows, the first max is multiplied by maxElem, then is added to the current value in position 0. Later, the result undergoes integer division by maxElem in line 21. I just want to know more about the general rule. This knowledge helps me understand in what situations I can use this rule.
Thanks.

We iterate over the entire list. The maxElem is initialized with 10, which is the maximum number in the list -1.
If the index is even, we want to store the Maximum numbers in descending order, so we take the mode of the max number lst[maxIdx] with the maxElem , multiply with maxElem and then store it in the list at even index number. This is achieved using the formula:

lst[i] += (lst[maxIdx] % maxElem) * maxElem 

We keep decrementing the maxIdx after performing an operation.

Similarly, if the index is odd, we take the mod of min number lst[minElem] with maxElem and multiply with maxElem :

lst[i] += (lst[minIdx] % maxElem) * maxElem

We keep incrementing the minIdx after performing an operation.

When the entire loop is traversed, we divide each element with maxElem to get the quotient value.
For the first element it is:
(9%10)*10 = 90 => lst[0].
lst[0] = 90/10 = 9

I hope this helps.
Anum Hassan|Developer Advocate

1 Like