Amazon | Onsite | SDE3 - Minimum number of steps to go from start to end of the string
Anonymous User
1102

Given string of alphabets. You can go from one character to either next character by paying the diff or to the same character without paying. You need to complete this in min cost

a g c h g d k g

The minimum path is a -> g -> g -> g

a -> g = 6
g -> g = 0
g -> g = 0

total cost = 6

So to clarify again:
We can move either one character to the next one and pay the cost of it
or, we can move to the same character as well if it occurs in the string and pay no cost.

Another example :
a b c d a
The cost of moving from first character 'a' to last character 'a' is 0. Hence this is considered.

vector<int> found(26, -1);
found[s[0]-'a'] = 0;

for (int i = 1; i < s.size(); ++i)
{
	if (found[s[i]-'a'] != -1) // 	if s[i] is seen before
	{
			found[s[i] - 'a'] = min (found[s[i] - 'a'], found[s[i-1] - 'a'] + abs(s[i-1] - s[i]););
	}
	else
	{
			found[s[i] - 'a'] = found[s[i-1] - 'a'] + abs(s[i-1] - s[i]);
	}
}

return found[s[n-1] - 'a'];
Comments (7)