There is an array A made of N integers. Your task is to choose as many integers from A as possible so that, when they are put in ascending order, all of the differences between all pairs of consecutive integers are equal. For example, for A = [4, 3, 5, 1, 4, 4], you could choose 1, 3, and 5 (with differences equal to 2) or 4, 4, and 4 (with differences equal to 0). So, answer in this case will be 3.
What is the maximum number of integers that can be chosen? Write a function.
Example 1 :
A = [4, 7, 1, 5, 3], function should return 4. 4 integers (7, 1, 5, 3) when put in ascending order the difference between all consecutive integers is 2.
Example 2 :
A = [12, 12, 12, 15, 10], function should return 3. It is optimal to chose all 3 integers with value 12.
Example 3 :
A = [18, 26, 18, 24, 24, 20, 22], function should return 5. 5 integers (18, 20, 22, 24, 26) when put in ascending order the difference between all consecutive integers is 2. Notice that we cannot pick any other integers, even though they occur more than once.
Approach that I used was, I sorted the array first & then applied Longest AP subsequence. It passed all the testcases but I wonder whether it was the correct approach or not. Can anyone help providing the optimal solution for this question.
My code :
int longestArithSeqLength(vector<int>& nums) {
int n = nums.size();
sort(begin(nums), end(nums)); //Just sort the array & then apply LAS logic
if(n <= 2)
return n;
//dp[i][diff] --> longest AP ending at ith index having common difference diff
unordered_map<int, int> dp[n]; //diff is key in map
int ans = INT_MIN;
//Similar logic of 1 approach of LIS
for(int i=1; i<n; i++) {
for(int j=0; j<i; j++) {
int diff = nums[i] - nums[j];
dp[i][diff] = (dp[j][diff] > 0) ? (dp[j][diff] + 1) : 2;
ans = max(ans, dp[i][diff]);
}
}
return ans;
}

