Maximum Total Area Occupied by Pistons Problem
Description
LeetCode Problem 3279.
There are several pistons in an old car engine, and we want to calculate the maximum possible area under the pistons.
You are given:
- An integer
height, representing the maximum height a piston can reach. - An integer array
positions, wherepositions[i]is the current position of pistoni, which is equal to the current area under it. - A string
directions, wheredirections[i]is the current moving direction of pistoni,'U'for up, and'D'for down.
Each second:
- Every piston moves in its current direction 1 unit. e.g., if the direction is up,
positions[i]is incremented by 1. - If a piston has reached one of the ends, i.e.,
positions[i] == 0orpositions[i] == height, its direction will change.
Return the maximum possible area under all the pistons.
Example 1:
Input: height = 5, positions = [2,5], directions = "UD"
Output: 7
Explanation:
The current position of the pistons has the maximum possible area under it.
Example 2:
Input: height = 6, positions = [0,0,6,3], directions = "UUDU"
Output: 15
Explanation:
After 3 seconds, the pistons will be in positions [3, 3, 3, 6], which has the maximum possible area under it.
Constraints:
1 <= height <= 10^61 <= positions.length == directions.length <= 10^50 <= positions[i] <= heightdirections[i]is either'U'or'D'.
Solution
Approach: Difference Map + Sweep over Time
Each piston bounces between 0 and height at speed 1, so the whole system repeats every 2 * height seconds and only the first period matters. The total area is the sum of the positions, which changes linearly with time between bounces.
Start with the current area and diff, the number of rising pistons minus the number of falling ones (the area's rate of change). Record when each piston changes direction in a map from time to a change of diff: an upward piston at pos turns at time height - pos (change -2) and again at 2 * height - pos (change +2); a downward piston turns at pos (change +2) and at height + pos (change -2). Sweep these times in increasing order, advance the area by (time gap) * diff, apply the change, and keep the maximum.
Complexity: O(n log n) time and O(n) space.
from collections import defaultdict
class Solution:
def maxArea(self, height: int, positions: List[int], directions: str) -> int:
delta = defaultdict(int)
diff = res = 0
for pos, dir in zip(positions, directions):
res += pos
if dir == "U":
diff += 1
delta[height - pos] -= 2
delta[height * 2 - pos] += 2
else:
diff -= 1
delta[pos] += 2
delta[height + pos] -= 2
ans = res
pre = 0
for cur, d in sorted(delta.items()):
res += (cur - pre) * diff
pre = cur
diff += d
ans = max(ans, res)
return ans