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, where positions[i] is the current position of piston i, which is equal to the current area under it.
  • A string directions, where directions[i] is the current moving direction of piston i, '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] == 0 or positions[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
Maximum Piston Area: Find Peak Total AreaChamber 1Chamber 2Chamber 3132Initial: Area = 1+3+2 = 6After 1s: Area = 2+2+3 = 7After 2s: Area = 3+1+4 = 8 ✓After 3s: Area = 4+0+3 = 7Maximum Total Area: 8
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
Asked in
Google 25 Amazon 18 Microsoft 15
28.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen