Ice floe leaps
MediumOnline Assessment
Find the richest route a seal can take across a line of drifting ice floes.
The string floes describes a row of ice floes, left to right. A digit character "0" to "9" is a floe holding that many fish. The character "#" is open water: the seal cannot land there.
The seal starts on the first floe and must finish on the last floe. Each leap goes forward by a distance of at least lo and at most hi floes (both inclusive), and the seal must land on a floe, never on open water. It eats all the fish on every floe it lands on, including the starting floe and the final floe. It may skip over open water and over floes it does not want.
Input: floes, the row of floes, and the leap limits lo and hi.
Output: the largest total number of fish the seal can collect over any legal route from the first floe to the last. If no legal route exists (this includes a start or a finish that is open water), return -1. A row with a single floe needs no leap, so the answer is that floe's fish, or -1 if it is open water. An empty row has no route: return -1.
The row can hold tens of thousands of floes and the leap range can be wide, so testing every possible leap from every floe will be too slow.
Example 1
- Input:
- ["5912",2,3]
- Output:
- 7
- Explanation
- The seal must make every leap 2 or 3 floes long. From floe 0 (5 fish) it can only land on floe 2 or floe 3, and from floe 2 it can never reach floe 3 with a leap of 1. So the only route is the single leap 0 -> 3, for 5 + 2 = 7 fish. Stepping through the 9-fish floe at index 1 is not allowed.
Example 2
- Input:
- ["40#0#7",1,2]
- Output:
- 11
- Explanation
- Floes 2 and 4 are open water, so they cannot be landed on, and a floe holding 0 fish can. The only legal route is 0 -> 1 -> 3 -> 5, collecting 4 + 0 + 0 + 7 = 11 fish.
Example 3
- Input:
- ["4##7",1,2]
- Output:
- -1
- Explanation
- From floe 0 the seal could only leap onto floe 1 or floe 2, and both are open water. It can never leave the start, so the answer is -1.
Constraints
0 <= floes.length <= 25,000- every character of
floesis a digit"0"to"9"or"#" 1 <= lo <= hi <= 25,000