Friday, July 21st

Today's problem is a variant of the Longest Increasing Subsequence, asking for the count of longest increasing subsequences.  Not just how long the longest sequence is, but how many of the longest sequences exist.

We begin with the basic LIS

    vector<int> dp(nums.size(), 1);
    for(int i=1; i<nums.size(); i++) {
        for(int j=0; j<i; j++) {
            if(nums[i]>nums[j]) {
                dp[i]=max(dp[i], dp[j]+1);
            }
        }
    }

we add an array for counting the number of paths

    vector<int> counts(nums.size(), 1);
   
and then modify what happens when a new subsequence is found, that is, what goes in the ellipses below 

    if(nums[j]<nums[i]) {
            ...
    }

If a new longest sequence is found, then we update the dp array, and set the counts of the paths equal to the number of paths before, since the total number of paths for the new longest subsequence is equal to the number of paths to the previous longest 

    if(dp[j]+1>dp[i]) {
        dp[i]=dp[j]+1;
        counts[i]=counts[j];
    }

Otherwise, if the longest sequence found is of equal length to a previously found longest sequence, then we have found an alternate sequence of the longest length.  So we add the two path counts together.  Because they're equal, dp array doesn't need to be updated.

   else if(dp[j]+1==dp[i]) {
        counts[i]+=counts[j];
    }

Then we return the total number of path counts to the longest increasing subsequence

    int mx=INT_MIN;
    for(int i=0; i<dp.size(); i++) {
        mx=max(mx,dp[i]);
    }
    int res=0;
    for(int i=0; i<nums.size(); i++) {
        if(dp[i]==mx) res+=counts[i];
    }
    return res;

Good problem for reinforcing ideas for dynamic programming and LIS

Thanks to akshycodes for clarifying how the counts array is updated when LISs are unequal

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th