LeetCode 1751: Maximum Number of Events That Can Be Attended II
LeetCode 1751 Solution Explanation
Explanation
To solve this problem, we can use dynamic programming. We will first sort the events based on their end days. Then, we will iterate through each event and for each event, we will consider two cases: either attend the current event or skip it. We will maintain a 2D dp array where dp[i][j] represents the maximum sum of values that can be obtained by attending j events from the first i events.
At each event, we will update the dp array based on the maximum value we can get by attending the current event or skipping it. Finally, the maximum value we can get will be the maximum value in the last row of the dp array.
The time complexity of this solution is O(nk) where n is the number of events and k is the maximum number of events we can attend. The space complexity is also O(nk) for storing the dp array.
LeetCode 1751 Solutions in Java, C++, Python
class Solution {
public int maxValue(int[][] events, int k) {
Arrays.sort(events, (a, b) -> Integer.compare(a[1], b[1]));
int n = events.length;
int[][] dp = new int[n + 1][k + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
int start = events[i - 1][0];
int end = events[i - 1][1];
int value = events[i - 1][2];
int prevEventIndex = findPrevEvent(events, i);
dp[i][j] = Math.max(dp[i - 1][j], dp[prevEventIndex][j - 1] + value);
}
}
return dp[n][k];
}
private int findPrevEvent(int[][] events, int currentIndex) {
int low = 0, high = currentIndex - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (events[mid][1] < events[currentIndex - 1][0]) {
if (events[mid + 1][1] < events[currentIndex - 1][0]) {
low = mid + 1;
} else {
return mid + 1;
}
} else {
high = mid - 1;
}
}
return 0;
}
}
Interactive Code Editor for LeetCode 1751
Improve Your LeetCode 1751 Solution
Use the editor below to refine the provided solution for LeetCode 1751. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...