Saturday, August 26th

 Pair Chain Lengths

Given a collection of pairs, where the first element is less than the second, find the longest chain that can be formed by placing pairs together, where the last element in the first pair is less than the first element in the second pair

The overlapping nature of the problem suggests dynamic programming.  We will employ a top-down approach coupled with a memo table.  The table will be of 1 dimension, as the lone state variable in the problem is the index in the pairs array

First, since any pair may be selected in any order, it will be helpful to sort the pairs array.  Also, we declare a few global variables to keep the function calls more readable.  This includes the memo table, initialized to be the length of pairs, with default value of 0;

int findLongestChain(vector<vector<int>>& pairs) {
n=pairs.size();
memo=vector<int>(n,0);
this->pairs=pairs;
sort(this->pairs.begin(), this->pairs.end());
        ...
    }

Then we define our dp function.  The function will take an integer (an index to the pairs array) and return the length of the longest chain starting from that index

int dp(int i) {
        ...  
    }

To begin the dp function, we check if the memo has already found an answer for the given index

if (memo[i] != 0) {
return memo[i];
}

Then comes the recurrence relation.  First we set the base case to 1, where we take the given pair and nothing else.  Then, we iterate through all pairs beginning with j=I+1 all the way to the end.  If the second value of the pair at index i is less than the first element of the pair in index j, then return 1+ the length of the chain at index j.  

    memo[i] = 1;
for (int j = i + 1; j < n; j++) {
if (pairs[i][1] < pairs[j][0]) {
memo[i] = max(memo[i], 1 + dp(j));
}
}

End the dp function by returning the memo'ed value

    int dp(int i) {
        ...
        return memo[i];
}

With the dp function set, we can find the longest length of any chain beginning at a given index.  So iterate through every index, execute dp(), then return the maximum length achieved.  Then return the answer.

    int ans = 0;
for (int i = 0; i < n; i++) {
ans = max(ans, dp(i));
}
return ans;

A solid medium dynamic programming problem.  Several different approaches using both 1 and 2 state variables.  Also a greedy method available by sorting the pairs according to second value, not the default first pair value.

Thanks to the Editorial for a 1-state-variable solution

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th