Chat app~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-55greedy
A chat network forwards a message along a row of relay servers, numbered from 0. The message starts at relay 0, and relay i can pass it forward by at most reach[i] places.
The network has one signal booster. It can be used once, on one hand-over, and it adds boost places to the reach of the relay that uses it. Relays can pass the message over fewer places than their reach allows.
You decide whether the message can get to the last relay.
Write can_reach_with_boost(reach, boost).
reach[i] is the farthest forward that relay i can pass the message. A relay may pass it any number of places from 1 up to its reach. A reach of 0 means that it cannot pass it on.boost to that relay's reach for that hand-over.true if the message can reach the last relay, and false otherwise. A row with one relay is already at the end.Input: reach = [2,2,0,0,3,1], boost = 1
Output: trueThe solution first finds how far the message gets without the booster. Then it picks the best relay to boost, and checks how far the message can go from there.
| Stage | What happens |
|---|---|
| No booster | Relay 0 reaches 2, relay 1 reaches 3, relays 2 and 3 add nothing. The message gets as far as relay 3 |
| Best boost | From relays 0 to 3, the boosted reaches are 3, 4, 3 and 4. The best is relay 4 |
| After the boost | Relay 4 can pass 3 places, which reaches relay 7, so the last relay, number 5, is reached |
The answer is true.
Input: reach = [2,2,0,0,3,1], boost = 0
Output: falseWithout a boost, the message gets as far as relay 3, and both relay 2 and relay 3 have a reach of 0. The last relay is out of reach.
Input: reach = [0,1,0,2,3], boost = 1
Output: falseRelay 0 has no reach. With the boost it can pass the message to relay 1, which reaches relay 2, and relay 2 has no reach. The last relay is out of reach.
1 ≤ len(reach) ≤ 100,000, and 0 ≤ reach[i] ≤ 100,0000 ≤ boost ≤ 100,000Trying every relay for the booster, and every hand-over from each relay, costs about 100,000 times 100,000 steps, which is 10,000,000,000. One pass for the farthest normal reach, one scan for the best boosted hand-over, and one more pass to extend it cost about 300,000 steps in all.