|
56 | 56 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
57 | 57 |
|
58 | 58 | ```python
|
59 |
| - |
| 59 | +class Solution: |
| 60 | + def longestSubsequence(self, arr: List[int], difference: int) -> int: |
| 61 | + dp, ans = defaultdict(int), 1 |
| 62 | + for num in arr: |
| 63 | + dp[num] = dp[num - difference] + 1 |
| 64 | + ans = max(ans, dp[num]) |
| 65 | + return ans |
60 | 66 | ```
|
61 | 67 |
|
62 | 68 | ### **Java**
|
63 | 69 |
|
64 | 70 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
65 | 71 |
|
66 | 72 | ```java
|
| 73 | +class Solution { |
| 74 | + public int longestSubsequence(int[] arr, int difference) { |
| 75 | + Map<Integer, Integer> dp = new HashMap<>(); |
| 76 | + int ans = 1; |
| 77 | + for (int num : arr) { |
| 78 | + dp.put(num, dp.getOrDefault(num - difference, 0) + 1); |
| 79 | + ans = Math.max(ans, dp.get(num)); |
| 80 | + } |
| 81 | + return ans; |
| 82 | + } |
| 83 | +} |
| 84 | +``` |
| 85 | + |
| 86 | +### **C++** |
| 87 | + |
| 88 | +```cpp |
| 89 | +class Solution { |
| 90 | +public: |
| 91 | + int longestSubsequence(vector<int>& arr, int difference) { |
| 92 | + unordered_map<int, int> dp; |
| 93 | + int ans = 1; |
| 94 | + for (int num : arr) { |
| 95 | + dp[num] = dp[num - difference] + 1; |
| 96 | + ans = max(ans, dp[num]); |
| 97 | + } |
| 98 | + return ans; |
| 99 | + } |
| 100 | +}; |
| 101 | +``` |
67 | 102 |
|
| 103 | +### **Go** |
| 104 | +
|
| 105 | +```go |
| 106 | +func longestSubsequence(arr []int, difference int) int { |
| 107 | + dp, ans := make(map[int]int), 1 |
| 108 | + for _, num := range arr { |
| 109 | + dp[num] = dp[num-difference] + 1 |
| 110 | + ans = max(ans, dp[num]) |
| 111 | + } |
| 112 | + return ans |
| 113 | +} |
| 114 | +
|
| 115 | +func max(a, b int) int { |
| 116 | + if a > b { |
| 117 | + return a |
| 118 | + } |
| 119 | + return b |
| 120 | +} |
68 | 121 | ```
|
69 | 122 |
|
70 | 123 | ### **...**
|
|
0 commit comments