Talentd
FleetCode

3279. Maximum Total Area Occupied by Pistons

Hard41.3% acceptancePremium elsewhere, free here

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.

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 <= 106
  • 1 <= positions.length == directions.length <= 105
  • 0 <= positions[i] <= height
  • directions[i] is either 'U' or 'D'.

Hints open one at a time

Hint 1
Simulate the process.
Hint 2
We only need to keep track of the times when a piston reaches one end and let’s call these critical points.
Hint 3
For each piston, find the first time it reaches one end and sort these times (these times are critical points).
Hint 4
Find a way to calculate the area difference between two consecutive critical points in constant time.
21:29
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
5
[2,5]
"UD"
Input
6
[0,0,6,3]
"UUDU"
Your code is saved on this device.Solution