Maximum Total Area Occupied by Pistons - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
height = 4, positions = [1,3,2], directions = "UDU"
›
Output:
8
💡 Note:
At time 2: piston 1 reaches position 3 (up from 1), piston 2 reaches position 1 (down from 3), piston 3 reaches position 4 (up from 2). Total area = 3+1+4 = 8
Example 2 — All Moving Up
$
Input:
height = 3, positions = [1,2], directions = "UU"
›
Output:
6
💡 Note:
Both pistons move up. At time 1: positions become [2,3], total = 5. At time 2: positions become [3,3] (piston 2 bounces), total = 6
Example 3 — Single Piston
$
Input:
height = 5, positions = [2], directions = "D"
›
Output:
5
💡 Note:
Piston moves down to 0, then up to maximum height 5. Maximum area is 5 when it reaches the top
Constraints
- 1 ≤ height ≤ 105
- 1 ≤ positions.length ≤ 104
- 0 ≤ positions[i] ≤ height
- directions.length == positions.length
- directions[i] is either 'U' or 'D'
Visualization
Tap to expand
Understanding the Visualization
1
Input
Pistons at positions [1,3,2] with directions UDU in chambers of height 4
2
Process
Track piston movements over time to find when total area is maximized
3
Output
Maximum total area is 8 (achieved at time t=2)
Key Takeaway
🎯 Key Insight: Pistons follow predictable bounce patterns - find optimal time when total area peaks
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code