1751. Maximum Number of Events That Can Be Attended II #1902
-
Topics: You are given an array of You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return the maximum sum of values that you can receive by attending events. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to maximize the sum of values obtained by attending at most Approach
Let's implement this solution in PHP: 1751. Maximum Number of Events That Can Be Attended II <?php
/**
* @param Integer[][] $events
* @param Integer $k
* @return Integer
*/
function maxValue($events, $k) {
$n = count($events);
if ($n == 0 || $k == 0) {
return 0;
}
usort($events, function($a, $b) {
return $a[1] - $b[1];
});
$endDays = array_column($events, 1);
$prevIndex = array_fill(0, $n, -1);
for ($i = 1; $i < $n; $i++) {
$left = 0;
$right = $i - 1;
while ($left <= $right) {
$mid = intdiv($left + $right, 2);
if ($endDays[$mid] < $events[$i][0]) {
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
$prevIndex[$i] = $right;
}
$dp = array_fill(0, $n, array_fill(0, $k + 1, 0));
for ($j = 1; $j <= $k; $j++) {
$dp[0][$j] = $events[0][2];
}
for ($j = 1; $j <= $k; $j++) {
for ($i = 1; $i < $n; $i++) {
$dp[$i][$j] = $dp[$i - 1][$j];
$prevVal = 0;
if ($prevIndex[$i] != -1) {
$prevVal = $dp[$prevIndex[$i]][$j - 1];
}
$currentOption = $events[$i][2] + $prevVal;
if ($currentOption > $dp[$i][$j]) {
$dp[$i][$j] = $currentOption;
}
}
}
$ans = 0;
for ($j = 0; $j <= $k; $j++) {
if ($dp[$n - 1][$j] > $ans) {
$ans = $dp[$n - 1][$j];
}
}
return $ans;
}
// Test cases
$events1 = [[1,2,4],[3,4,3],[2,3,1]];
$k1 = 2;
echo maxValue($events1, $k1) . PHP_EOL; // Output: 7
$events2 = [[1,2,4],[3,4,3],[2,3,10]];
$k2 = 2;
echo maxValue($events2, $k2) . PHP_EOL; // Output: 10
$events3 = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]];
$k3 = 3;
echo maxValue($events3, $k3) . PHP_EOL; // Output: 9
?> Explanation:
This approach efficiently leverages sorting, binary search, and dynamic programming to solve the problem within feasible time complexity, making it suitable for large input sizes as specified in the constraints. |
Beta Was this translation helpful? Give feedback.
We need to maximize the sum of values obtained by attending at most
k
non-overlapping events. Each event has a start day, end day, and a value. The key challenge is to select events such that no two events overlap, and the sum of their values is maximized while attending at mostk
events.Approach