796. Maximum Total Area Occupied by Pistons
In an old car engine, several pistons oscillate between the bottom (position 0) and a fixed maximum height. The “area” beneath a piston is equal to its current vertical position. Given each piston’s starting position and movement direction, determine the maximum total area (i.e. the sum of the positions of all pistons) that can be observed at any integer second.
You are given:
- An integer height representing the maximum height a piston can reach.
- An integer array positions, where positions[i] is the current position (and thus the area under) piston i.
- A string directions, where directions[i] is either 'U' (meaning piston i is moving upward) or 'D' (meaning it is moving downward).
Each second, the following occurs simultaneously for every piston:
- Movement: Every piston moves 1 unit in its current direction. That is, if the piston’s direction is upward, its position increases by 1; if downward, its position decreases by 1.
- Direction Change: After moving, if a piston’s new position is either 0 or height, it will reverse its direction for subsequent moves.
Return the maximum possible total area under all the pistons that can be achieved at some point in time.
Example 1:
Input : height = 4, positions = [1], directions = "U"
Output : 4
Explanation :
At time 0, the piston is at position 1 (total area = 1). It moves upward one unit per second, reaching position 4 after 3 seconds. Since 4 is the maximum height, the greatest area observed is 4.
Example 2:
Input : height = 7, positions = [3, 7], directions = "DD"
Output : 10
Explanation :
Initially, the pistons are at positions 3 and 7 (total area = 10).
- Piston 1 (position 3, moving down) will decrease its position, and
- Piston 2 is at the top (position 7, moving down) so it will move to 6 next.
- No future configuration results in a combined area exceeding 10.
Now Your Turn!
Pick the correct output for the given inputInput : height = 8, positions = [2, 4, 8], directions = "UUD"
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= height <= 106
- 1 <= positions.length == directions.length <= 105
- 0 <= positions[i] <= height
- directions[i] is either 'U' or 'D'.