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.
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
Comments
Post a Comment