-
Notifications
You must be signed in to change notification settings - Fork 0
/
1937. Maximum Number of Points with Cost
51 lines (42 loc) · 1.62 KB
/
1937. Maximum Number of Points with Cost
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public long maxPoints(int[][] points) {
int rows = points.length, cols = points[0].length;
long[] previousRow = new long[cols];
// Initialize the first row
for (int col = 0; col < cols; ++col) {
previousRow[col] = points[0][col];
}
// Process each row
for (int row = 0; row < rows - 1; ++row) {
long[] leftMax = new long[cols];
long[] rightMax = new long[cols];
long[] currentRow = new long[cols];
// Calculate left-to-right maximum
leftMax[0] = previousRow[0];
for (int col = 1; col < cols; ++col) {
leftMax[col] = Math.max(leftMax[col - 1] - 1, previousRow[col]);
}
// Calculate right-to-left maximum
rightMax[cols - 1] = previousRow[cols - 1];
for (int col = cols - 2; col >= 0; --col) {
rightMax[col] = Math.max(
rightMax[col + 1] - 1,
previousRow[col]
);
}
// Calculate the current row's maximum points
for (int col = 0; col < cols; ++col) {
currentRow[col] = points[row + 1][col] +
Math.max(leftMax[col], rightMax[col]);
}
// Update previousRow for the next iteration
previousRow = currentRow;
}
// Find the maximum value in the last processed row
long maxPoints = 0;
for (int col = 0; col < cols; ++col) {
maxPoints = Math.max(maxPoints, previousRow[col]);
}
return maxPoints;
}
}