Saturday, July 15th

 Multi-dimensional Dynamic Programming is the topic for today's challenge

Given an array of events, where each event has a start time, end time, and value... And given an integer k... Determine the maximum total value of events you can attend, attending up to k events

It's obvious a greedy approach won't work.  Furthermore, because the problem asks for a maximum value, and also because a decision to attend an event depends on earlier decisions, this problem can likely be solved with dynamic programming

First we try to figure out the state variables: the current time is primary, and since the question limits us to k events, then another variable is the number of events

Next up is base cases.  If the current time equals the array length, we have reached the end.  Also, if the number of events attended equals k, then we have also reached the end.  In code this is:

    if(curIndex == eventsGlobal.size() || count==kGlobal) {
return 0;
 }

As we will see later, it is also necessary to track the end time of an event.  So in all, the dfs signature is

    int dfs(int curIndex, int count, int prevEndingTime) { }

Where curIndex is the current time, count is the number of events attended, and prevEndingTime is the end of the most recently selected event

We add an extra check to make sure the current index doesn't occur before the end of the previous event:

    if(prevEndingTime >= eventsGlobal[curIndex][0]) {
return dfs(curIndex+1, count, prevEndingTime);
}

Lastly, but most importantly,  is the recurrence relation.  If we accept a given event, then we take the events value, then cannot attend another event until after the accepted event's end time.  Otherwise, if we pass on a current event, we perform the function at the current index + 1

    int ans = max( dfs(curIndex+1, count, prevEndingTime),
           dfs(curIndex+1, count+1, eventsGlobal[curIndex][1]) + eventsGlobal[curIndex][2]);

All together, the code looks like:

        
    //global variables
    vector<vector<int> > eventsGlobal;
int kGlobal;
vector<vector<int> >dp;

int dfs(int curIndex, int count, int prevEndingTime) {
if(curIndex == eventsGlobal.size() || count==kGlobal) {
return 0;
}

if(prevEndingTime >= eventsGlobal[curIndex][0]) {
return dfs(curIndex+1, count, prevEndingTime);
}

if( dp[curIndex][count] != -1) {
return dp[curIndex][count];
}

int ans = max( dfs(curIndex+1, count, prevEndingTime),
dfs(curIndex+1, count+1, eventsGlobal[curIndex][1]) + eventsGlobal[curIndex][2]);
dp[curIndex][count]=ans;
return ans;

}

int maxValue(vector<vector<int>>& events, int k) {
sort(events.begin(), events.end());
dp =vector<vector<int> >(events.size(), vector<int>(k+1, -1));
kGlobal =k;
eventsGlobal=events;

return dfs(0,0,-1);
}

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th