The Longest Stretch of Glory
In preparation for the temple’s Festival of Lights, the apprentices are tasked with inspecting the sacred light string. Each bulb is represented by 1
if it’s lit and 0
if it’s not. But there’s a catch — Chef Bao is offering extra dumplings to the apprentice who can find the longest stretch of glowing bulbs! Naturally, chaos ensues as everyone races to prove their skills.
Your task is to find the starting index of the longest stretch of consecutive glowing bulbs (1
s). If multiple stretches have the same length, return the start of the first one. And if there are no glowing bulbs at all, you might as well go and help in the kitchen or just return -1
.
Example Input:
lights = "11011101111"
Example Output:
7
To solve this task:
- Track the Start and Length:
- Use a pointer variable
start
to track where a sequence of 1s begins. - Keep a variable
max_length
to store the maximum length of glowing bulbs found so far. - Use another variable
max_start
to remember the starting index of the longest stretch.
- Use a pointer variable
- Traverse the String:
- For each bulb:
- If it’s 1, check if it starts a new sequence or continues the current one.
- If it’s 0, calculate the length of the previous sequence and update
max_length
andmax_start
if necessary.
- Handle the Final Sequence:
- After the loop, check if the last sequence of glowing bulbs is the longest.
- Return the Result:
- Return
max_start
, which holds the index of the longest stretch. If no bulbs are glowing, return -1—but don’t tell Chef Bao.
- Return