![]() |
VOOZH | about |
Given a string s containing lowercase English letters.
Find the maximum possible difference between the starting index and the ending index. If it is not possible to choose a starting index, return -1.
Examples :
Input: s = "aaabcb"
Output: 5
Explanation: Start at index 0 ('a'), jump to index 5 ('b'). Difference = 5 - 0 = 5.Input: s = "xynjir"
Output: -1
Explanation: The string does not contain any character 'a'. So, the answer is -1.Input: s = "abcbzzd"
Output: 6
Explanation: Start from index 0 ('a'). Jump to index 1 ('b') because 'b' is the next alphabet character. Jump to index 2 ('c') because 'c' is the next character after 'b'. Jump to index 6 ('d') because 'd' is the next character after 'c'.
Table of Content
The idea is to recursively explore all possible jump sequences starting from every index containing 'a'. For each next index, try all possible positions on the right containing the next alphabet character and continue the recursion from there.
5
The idea is to store the farthest reachable index from every position. For each index, recursively explore all possible jumps to the next alphabet character and store the result. This avoids recalculating the same index multiple times, but each state still scans the remaining part of the string to find possible jumps.
5
The idea is to process the string from right to left because every jump is only allowed towards the right side. While traversing, maintain the farthest reachable index for each character. For the current character, if the next alphabet character has already been processed, we can directly use its farthest reachable index to determine the farthest position reachable from the current index. This avoids checking all possible jumps and allows each character to be processed in constant time.
5