[LeetCode] Maximum Total Area Occupied by Pistons

3279. Maximum Total Area Occupied by Pistons

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
  • An integer array positions, where positions[i] is the current position of piston i
  • 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

class Solution {
public:
long long maxArea(int height, vector<int>& positions, string directions) {
long long res = 0, now = 0, cnt = 0;
vector<int> A(2 * height + 1);
for(int i = 0; i < positions.size(); i++) {
now += positions[i];
if(positions[i] == 0) directions[i] = 'U';
if(positions[i] == height) directions[i] = 'D';
if(directions[i] == 'U') {
int mi = height - positions[i];
A[mi] -= 1;
A[mi+height] += 1;
cnt++;
} else {
A[positions[i]] += 1;
A[positions[i] + height] -= 1;
}
}
res = max(res, now);
for(int i = 0; i <= 2 * height; i++) {
cnt += A[i];
now = now + cnt - (positions.size() - cnt);
res = max(res, now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/05/PS/LeetCode/maximum-total-area-occupied-by-pistons/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.