Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit eff2f61

Browse files
committed
Time: 709 ms (74.54%), Space: 133 MB (51.66%) - LeetHub
1 parent 429b0e5 commit eff2f61

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution {
2+
public:
3+
4+
/*
5+
For every event, I've two options. Whether I choose that event or not.
6+
If choose, then I add its value to my answer. If not choosen I move forward to the next event.
7+
Now if I select a event, my next event has to have start time > end time of choosen event. Also of all the possible next events I should choose the one with max value
8+
To select the next event with start time > end time of choosen event, I can do a Binary search.
9+
What to select the Max value I can find the value of all legal subsets possible, and select the maximum of all the values.
10+
*/
11+
vector<int> start;
12+
int dp[100002][2];
13+
14+
int solve(vector<vector<int>>& events, int i, int choose){
15+
if(i>=events.size()){
16+
return 0;
17+
}
18+
19+
if(choose>=2){ // since I cannot chose more than two elemnts.
20+
return 0;
21+
}
22+
23+
if(dp[i][choose]!=-1){
24+
return dp[i][choose];
25+
}
26+
27+
int idx = upper_bound(start.begin(),start.end(),events[i][1])-start.begin(); // binary search to find the next event's index
28+
29+
return dp[i][choose]=max(events[i][2]+solve(events,idx,choose+1),solve(events,i+1,choose)); //either I select an event, or I dont
30+
31+
}
32+
33+
int maxTwoEvents(vector<vector<int>>& events) {
34+
35+
for(int i=0;i<100002;i++){
36+
for(int j=0;j<2;j++){
37+
dp[i][j]=-1;
38+
}
39+
}
40+
int n = events.size();
41+
//sort elemts acc to start time
42+
sort(events.begin(),events.end());
43+
44+
start.clear();
45+
for(int i=0;i<n;i++){
46+
start.push_back(events[i][0]);
47+
}
48+
49+
return solve(events,0,0);
50+
}
51+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /