Friday, July 14th

 Given an array and an integer difference, find the longest subsequence where the difference between neighbors is difference.  Problem here.

The problem echoes the Longest Increasing Subsequence (LIS) problem, a classic dynamic programming problem.  But the solution is actually much easier and straightforward.  Whereas with LIS is only looking for an increasing subsequence, at a value a[i] we can look for any value less than a[i].  But with the given problem, for a given value a[i] we only need to check if a[i]-2 has been seen yet.  Checking if a given value has been seen is a good situation of a hashmap.

    unordered_map<int, int> hashmap;

The hashmap will be keyed by a number the search array, and the value will be the length of the arithmetic subsequence leading up to and including the key;

Then we simply iterate through the array, and for each value in the array, we check if the value - difference has been seen.  If so, we increment the subsequence length by one, otherwise enter a value of 

        unordered_map<int, int> hashmap;
int ans_len = 1;
int num, len;
for(int i=0; i<arr.size(); i++) {
num=arr[i];
len=0;
if( hashmap.find(num-difference) != hashmap.end() ) {
len=hashmap[num-difference];
}
hashmap[num]=len+1;
ans_len=max(ans_len,len+1);
}
return ans_len;
Straightforward solution, interesting use of a hashmap for dynamic programming

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th