LeetCode 1751. Maximum Number of Events That Can Be Attended II
Dynamic Programming + Binary Search
PreviousLeetcode 1727. Largest Submatrix With RearrangementsNextLeetCode 1754. Largest Merge Of Two Strings
Last updated
Dynamic Programming + Binary Search
Last updated
Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2
Output: 7
Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2
Output: 10
Explanation: Choose event 2 for a total value of 10.
Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events.Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3
Output: 9
Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.class Solution {
public:
int maxValue(vector<vector<int>>& events, int k) {
auto cmp = [](const vector<int>& lhs, const vector<int>& rhs) {
return lhs[1] < rhs[1];
};
sort(events.begin(), events.end(), cmp);
int n = events.size();
vector<vector<int>> dp(n+1, vector<int>(k+1, 0));
for (int i = 1; i <= n; i++) {
int non_overlap_index = 0;
for (int l = i - 1; l >= 1; l--) {
if (events[l-1][1] < events[i-1][0]) {
non_overlap_index = l;
break;
}
}
for (int j = 1; j <= k; j++) {
dp[i][j] = max(dp[non_overlap_index][j-1] + events[i-1][2], dp[i-1][j]);
}
}
return dp[n][k];
}
};