Let the optimal parking spot be
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,
Where,
Starting from
Let’s look at an example. Suppose
Here’s the solution in C++
:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
int main(int argc, char const *argv[]) | |
{ | |
int T; std::cin >> T; | |
while(T--){ | |
int n; std::cin >> n; | |
int mx = 0, mn = 100; | |
for(int i = 0 ; i < n ; ++i){ | |
int x; std::cin >> x; | |
mx = std::max(mx, x); | |
mn = std::min(mn, x); | |
} | |
std::cout << 2 * (mx - mn) << '\n'; | |
} | |
return 0; | |
} |
Sharing is caring. Share this story in...
Share: Twitter Facebook LinkedIn