Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Least cost path in a sorted array

Given a sorted array A e.g. {4,9,10,11,19}. The cost for moving from i->j is abs(A[j]-A[i]). Start from a given element e.g. 10. Find out the least cost path without visiting same element twice. So in this example solution would be 10->9->4->11->19 i.e. 1 + 5 + 7 + 8 = 21.

I tried to solve this using nearest neighbor approach.

 i = start;
 While (array is not empty)
    ldiff = A[i] - A[i-1]
    rdiff = A[i+1] - A[i]
    (ldiff < rdiff) ? sum += ldiff : sum += rdiff
    remove A[i]

This solution does not work in every case. I have realised that this is TSP problem. What could be the best approach to solve this problem? Shall I use TSP heuristics like Christofides or some other algorithm?

like image 551
Prashant Ranjan Avatar asked Apr 11 '26 13:04

Prashant Ranjan


2 Answers

for your case least cost is 21, see

10->9->4->11->19 ==>  1 + 5 + 7 + 8 = 21.

I think, for common case, if you start from i-th position, least cost is path, minimum of

A[i]->A[i-1]-> ...->A[1] -> A[i+1] -> A[i+2] -> ...->A[n]  and

A[i]->A[i+1]-> ... ->A[n] ->A[i-1] ->A[i-2] -> ...->A[1]
like image 148
Khurshid Normuradov Avatar answered Apr 13 '26 05:04

Khurshid Normuradov


Process either the smaller or the largest element, depending which is closer (in value, not index) to the starting element, then simply process the remaining elements to the right or to the left (depending on whether we processed the smallest or the largest element).

So, given 4,9,10,11,19 starting from 10:

The distance from 10 to the smallest element 4 is 6, the distance from 10 to the largest element 19 is 9, so move to 4.

Then process the remaining elements in sorted order - 9, 11, 19.

This gives us 10 -> 4 -> 9 -> 11 -> 19, which costs 6 + 5 + 2 + 8 = 21.

This can be done in O(n).

Note:

It's worth noting that as long as we first move towards the closest side, then towards the other side (regardless of which elements we process when, as long as we don't change direction more than once), we'll get an optimal result.

That's why 10 -> 9 -> 4 -> 11 -> 19 also gives 21.

like image 44
Bernhard Barker Avatar answered Apr 13 '26 04:04

Bernhard Barker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!