C# || How To Find Longest Arithmetic Subsequence Of An Array Using C#

The following is a module with functions which demonstrates how to find the longest arithmetic subsequence of an array using C#.


1. Longest Arithmetic Subsequence Length – Problem Statement

Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.

Recall that a subsequence of an array nums is a list nums[i1], nums[i2], …, nums[ik] with 0 <= i1 < i2 < … < ik <= nums.length – 1, and that a sequence seq is arithmetic if seq[i+1] – seq[i] are all the same value (for 0 <= i < seq.length – 1).

Example 1:


Input: nums = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.

Example 2:


Input: nums = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].

Example 3:


Input: nums = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].


2. Longest Arithmetic Subsequence Length – Solution

The following is a solution which demonstrates how to find the longest arithmetic subsequence of an array.

The main idea in this solution is to maintain a dictionary map array of the differences seen at each index, where dp[index][diff] holds the frequency count at that index, for that specific diff.

Each item in the array is considered and checked against to their items to the left.

For each number (i,j) we determine the difference d = nums[i] – nums[j] and keep a count of the frequency the difference has been seen.

In the end, the max difference frequency is returned.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


4
3
4

Was this article helpful?
👍 YesNo

Leave a Reply