1937. Maximum Number of Points with Cost #335
-
Topics: You are given an To gain points, you must pick one cell in each row. Picking the cell at coordinates However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows Return the maximum number of points you can achieve.
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can break down the solution into several steps: Step 1: Define the DP ArrayWe will use a 2D array Step 2: Initialize the DP ArrayInitialize the first row of Step 3: Calculate DP Values for Each RowFor each subsequent row, we calculate the maximum possible points for each column considering the costs of switching from the previous row. To efficiently calculate the transition from row
Step 4: Update DP for Each RowFor each column
Step 5: Return the Maximum Value from the Last RowThe result will be the maximum value in the last row of the Let's implement this solution in PHP: 1937. Maximum Number of Points with Cost <?php
function maxPoints($points) {
$m = count($points);
$n = count($points[0]);
$dp = $points[0];
for ($i = 1; $i < $m; $i++) {
// Initialize left and right arrays
$left = array_fill(0, $n, 0);
$right = array_fill(0, $n, 0);
// Calculate the left array
$left[0] = $dp[0];
for ($j = 1; $j < $n; $j++) {
$left[$j] = max($left[$j - 1] - 1, $dp[$j]);
}
// Calculate the right array
$right[$n - 1] = $dp[$n - 1];
for ($j = $n - 2; $j >= 0; $j--) {
$right[$j] = max($right[$j + 1] - 1, $dp[$j]);
}
// Update dp for the current row
for ($j = 0; $j < $n; $j++) {
$dp[$j] = $points[$i][$j] + max($left[$j], $right[$j]);
}
}
return max($dp);
}
// Example usage:
$points1 = [[1, 5], [2, 3], [4, 2]];
$points2 = [[2, 4, 3], [5, 6, 4]];
echo maxPoints($points1); // Output: 11
echo maxPoints($points2); // Output: 9
?> Explanation:
This approach has a time complexity of (O(m \times n)), which is efficient given the constraints. |
Beta Was this translation helpful? Give feedback.
We can break down the solution into several steps:
Step 1: Define the DP Array
We will use a 2D array
dp
wheredp[i][j]
represents the maximum points we can achieve by selecting the cell at rowi
and columnj
.Step 2: Initialize the DP Array
Initialize the first row of
dp
to be the same as the first row ofpoints
since there are no previous rows to subtract the cost.Step 3: Calculate DP Values for Each Row
For each subsequent row, we calculate the maximum possible points for each column considering the costs of switching from the previous row.
To efficiently calculate the transition from row
i-1
to rowi
, we can use two auxiliary arraysleft
andright
:left[j]
will store the maximum val…