Skip to content

Commit 470aa4f

Browse files
authored
Update maximum-score-of-non-overlapping-intervals.cpp
1 parent 81271d9 commit 470aa4f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

C++/maximum-score-of-non-overlapping-intervals.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,41 @@
33

44
// dp, binary search
55
class Solution {
6+
public:
7+
vector<int> maximumWeight(vector<vector<int>>& intervals) {
8+
static const int K = 4;
9+
map<tuple<int, int, int>, int> lookup;
10+
for (int i = 0; i < size(intervals); ++i) {
11+
const int l = intervals[i][0];
12+
const int r = intervals[i][1];
13+
const int w = intervals[i][2];
14+
if (!lookup.count(tuple(r, l, w))) {
15+
lookup[tuple(r, l, w)] = i;
16+
}
17+
}
18+
vector<tuple<int, int, int>> sorted_intervals;
19+
for (const auto& [k, _] : lookup) {
20+
sorted_intervals.emplace_back(k);
21+
}
22+
vector<vector<pair<int64_t, vector<int>>>> dp(size(sorted_intervals) + 1, vector<pair<int64_t, vector<int>>>(K + 1));
23+
for (int i = 0; i + 1 < size(dp); ++i) {
24+
const int j = distance(cbegin(sorted_intervals), upper_bound(cbegin(sorted_intervals), cend(sorted_intervals), tuple(get<1>(sorted_intervals[i]), 0, 0))) - 1;
25+
const int idx = lookup[sorted_intervals[i]];
26+
for (int k = 1; k < size(dp[i]); ++k) {
27+
auto new_dp = pair(get<0>(dp[j + 1][k - 1]) - get<2>(sorted_intervals[i]), get<1>(dp[j + 1][k - 1]));
28+
auto& arr = get<1>(new_dp);
29+
arr.insert(upper_bound(begin(arr), end(arr), idx), idx);
30+
dp[i + 1][k] = min(dp[i][k], new_dp);
31+
}
32+
}
33+
return get<1>(dp[size(sorted_intervals)][K]);
34+
}
35+
};
36+
37+
// Time: O(nlogn + n * k^2)
38+
// Space: O(n * k^2)
39+
// dp, binary search
40+
class Solution2 {
641
public:
742
vector<int> maximumWeight(vector<vector<int>>& intervals) {
843
static const int K = 4;

0 commit comments

Comments
 (0)