1721. Ice Floe Merger
Ice floes drift along a narrow channel. The array floes lists them from left to right: the absolute value is the floe's mass and the sign is its direction (positive moves right, negative moves left). All floes move at the same speed, so two floes only meet when a right-mover is immediately followed by a left-mover.
When they meet they freeze into a single floe whose mass is the sum of the two masses and whose direction is that of the heavier one. If the masses are equal, both floes vanish. The new floe keeps drifting and may collide again with its new neighbours. Return the signed masses of the floes that survive once no more collisions are possible, from left to right, as a long[] (an empty array if nothing survives). A stack gives O(n) time and O(n) space; repeated passes are too slow.
Example 1
- Input:
- floes = [5,10,-5]
- Output:
- [5,15]
- Explanation:
The floe 10 hits -5 and merges into a right-moving floe of mass 15 (10 is heavier); it never meets a left-mover again, so the result is [5, 15].
Example 2
- Input:
- floes = [8,-8]
- Output:
- []
- Explanation:
Equal masses annihilate each other, leaving nothing.
Example 3
- Input:
- floes = [3,-5,4]
- Output:
- [-8,4]
- Explanation:
3 meets -5 and merges into a left-moving floe of mass 8; it leaves the ice moving left, and 4 moves right, giving [-8, 4].
Constraints
1 ≤ n ≤ 105; 1 ≤ |floes[i]| ≤ 109; floes[i] ≠ 0
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)