在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an integer array
Example 1: Input: arr = [1,2,3,4], difference = 1 Output: 4 Explanation: The longest arithmetic subsequence is [1,2,3,4]. Example 2: Input: arr = [1,3,5,7], difference = 1 Output: 1 Explanation: The longest arithmetic subsequence is any single element. Example 3: Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2 Output: 4 Explanation: The longest arithmetic subsequence is [7,5,3,1].
Constraints:
给你一个整数数组
示例 1: 输入:arr = [1,2,3,4], difference = 1 输出:4 解释:最长的等差子序列是 [1,2,3,4]。 示例 2: 输入:arr = [1,3,5,7], difference = 1 输出:1 解释:最长的等差子序列是任意单个元素。 示例 3: 输入:arr = [1,5,7,8,5,3,4,2,1], difference = -2 输出:4 解释:最长的等差子序列是 [7,5,3,1]。
提示:
Runtime: 748 ms
Memory Usage: 23.9 MB
1 class Solution { 2 func longestSubsequence(_ arr: [Int], _ difference: Int) -> Int { 3 var dp:[Int:Int] = [Int:Int]() 4 var longest:Int = 0 5 for i in 0..<arr.count 6 { 7 dp[arr[i]] = dp[arr[i]-difference,default:0] + 1 8 longest = max(longest, dp[arr[i],default:0]) 9 } 10 return longest 11 } 12 }
|
请发表评论