Let the optimal parking spot be $x$. The position of the stores are given as $a_1, a_2, a_3,\ldots,a_n$. It is easy to see that,
\[min(a_1, a_2, a_3,\ldots,a_n) \leq x \leq max(a_1, a_2, a_3,\ldots,a_n)\]
Now let’s sort the store positions for ease of calculation. Sorting, however, won’t change the output. Because from the optimal spot, we have to visit all the store positions anyway. After sorting, the store positions become,
\[ a_1^\prime \leq a_2^\prime \leq \ldots \leq a_n^\prime \]
Where, $a_1^\prime = min(a_1, a_2, a_3,\ldots,a_n)$ and $a_n^\prime = max(a_1, a_2, a_3,\ldots,a_n)$.
Starting from $x$, the cost of walking then becomes,
\[ (\cancel{x} - a_1^\prime) + (\cancel{a_2^\prime} - a_1^\prime) + (\cancel{a_3^\prime} - \cancel{a_2^\prime}) + \ldots + (a_n^\prime - \cancel{a_{n-1}^\prime}) + (a_n^\prime - \cancel{x}) \] \[ = 2 * (a_n^\prime - a_1^\prime) \]
Let’s look at an example. Suppose $4$ store locations are $24,13,89,37$. Now assuming $x$ as the optimal parking spot, our calculation becomes,
\[ (x - 13) + (24 - 13) + (37 - 24) + (89 - 37) + (89 - x) \] \[ = 2 * (89 - 13)\] \[ = 152 \]
Here’s the solution in C++
:
Sharing is caring. Share this story in...
Share: Twitter Facebook LinkedIn