Title: 5214. longest sequence given difference
Give you an integer array arr
and an integer difference
, you find arr
between all adjacent elements equal to a given difference difference
of the arithmetic sequence, and returns the arithmetic longest sequence length.
Example 1:
Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: arithmetic longest sequence is [1,2,3,4].
Example 2:
Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The arithmetic sequence is the longest of any single element.
Example 3:
Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The arithmetic sequence is the longest [7,5,3 ,1].
prompt:
1 <= arr.length <= 10^5
-10^4 <= arr[i], difference <= 10^4
answer:
Map<key, value>
Save to key
end of the sequence of maximum length.
Through the array arr
, the number of k
predecessor nodes is pre = k - difference
, therefore k
sequence length plus 1 end, updates the maximum (return value), and updates map
the key = k
time of value
.
time complexity:
, without regard toHashMap
find the time complexity
and space complexity:uncertain
Java:
class Solution {
public int longestSubsequence( int[] arr,
int difference) {
Map<Integer, Integer> map = new HashMap<>();
int ret = 0;
for (int k : arr) {
int pre = k - difference;// 前驱
// 序列增加数k,因此长度加1
int len = map.getOrDefault(pre, 0) + 1;
ret = Math.max(ret, len);
map.put(k, len);// 更新map
}
return ret;
}
}