Longest Arithmetic Subsequence of Given Difference LeetCode solution in Java

1
class Solution {
2
public int longestSubsequence(int[] arr, int difference) {
3
// Storing the final answer as 1
4
int length = arr.length, max_length = 1;
5
HashMap<Integer, Integer> Terms_till_now = new HashMap<>();
6
for (int i = 0; i < length; i++) {
7
/*
8
Find the number of terms, till curr_element - difference , say terms
9
Mapping 1 + n to the current term of the sequence, i.e. curr_element
10
*/
11
int terms =
12
((Terms_till_now.get(arr[i] - difference) == null)
13
? 0
14
: Terms_till_now.get(arr[i] - difference));
15
Terms_till_now.put(arr[i], 1 + terms);
16
max_length = Math.max(max_length, 1 + terms);
17
}
18
return max_length;
19
}
20
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0