Skip to content

Commit e7ff4d4

Browse files
add 1218
1 parent 5b52809 commit e7ff4d4

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

contest/src/main/java/com/github/contest/Execute.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.github.contest
22

33

4-
import com.github.contest.dp.maxNonDecreasingLength
4+
import com.github.contest.dp.longestSubsequence
55
import java.util.TreeMap
66

77

@@ -11,7 +11,7 @@ import java.util.TreeMap
1111

1212
fun main() {
1313

14-
maxNonDecreasingLength(intArrayOf(11, 7, 7, 9), intArrayOf(19, 19, 1, 7))
14+
longestSubsequence(intArrayOf(2, -6, -3, -6, 2, 0), -2).also { println(it) }
1515
}
1616

1717
fun generateTesting() {

contest/src/main/java/com/github/contest/dp/DpLeetcode.kt

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,25 @@ fun maxNonDecreasingLength(nums1: IntArray, nums2: IntArray): Int {
522522
return maxLen
523523
}
524524

525+
/**
526+
* 1218. Longest Arithmetic Subsequence of Given Difference
527+
*/
528+
529+
530+
fun longestSubsequence(arr: IntArray, difference: Int): Int {
531+
val dp = mutableMapOf<Int, Int>()
532+
var maxLen = 0
533+
534+
for (num in arr) {
535+
val prev = num - difference
536+
val len = dp.getOrDefault(prev, 0) + 1
537+
dp[num] = len
538+
maxLen = maxOf(maxLen, len)
539+
}
540+
541+
return maxLen
542+
}
543+
525544

526545

527546

0 commit comments

Comments
 (0)