Approach
Consensus
- There are 2 ways to move around, one is left to right, another one is right right to left
- When we are moving in that particular direction, we check if the distance from current location to the next location is shorter than from current location to the previous location. If yes, then
1
, else we have to take the distance between the current location to the next location
Details
-
Finding the cost of travelling from current location to the next location can be solved easily with Greedy Algorithm
-
Then for each start-end pair, we just need to obtain the sum of the cost between the start location and the end location
-
If we observe carefully, obtaining the sum of cost between 2 locations. We can optimise the time complexity with Range Sum Query!
-
But we need to mindful that instead of , we use , because we start from location , the cost is , we want to know what is the cost of travelling from location to location , not travelling to until
-
The travelling from left to right is pretty straight forward, the tricky part is travelling from right to left
-
For me, I set the prefix sum array in this way: index 0 means the cost of travelling from most right to most left, so the more right we move in the prefix sum, the smaller the cost
-
Then when we are given a starting location(higher value) and end location(lower value), we simply
prefix_sum[end location]
-prefix_sum[start location]
to obtain the cost. You can think of it like cost of travelling first 5 locations - cost of travelling first 3 locations = cost of travelling last 2 cities
Conclusion
- The problem uses greedy algorithm, prefix sum (with a small twist) to solve
Space & Time Analysis
The analysis method we are using is Algorithm Complexity Analysis
Space - O(n)
- Ignore input size & language dependent space
- We are creating 2 Dynamic Array to implement prefix sum
Time - O(n + m)
- O(n) to populate the prefix sum, O(m) to handle all the pairs of starting location to ending location
Codes
1st Attempt (Java)
Personal Reflection
- Why it takes so long to solve: I keep getting Timeout Error with just the Greedy Algorithm. I failed to see that with Prefix Sum (前缀和), we are able to obtain the cost of travelling from one city to another in constant time
- What you could have done better: Practice more on prefix sum, and be dead comfortable with Range Sum Query
- What you missed: Prefix Sum
- Ideas you’ve seen before: Greedy and prefix sum
- Ideas you found here that could help you later: Prefix sum’s range sum query
- Ideas that didn’t work and why: just greedy algorithm alone, the time complexity is too large