@@ -350,4 +350,70 @@ fun maxAbsoluteSum(nums: IntArray): Int {
350
350
}
351
351
352
352
return maxOf(maxSoFar, abs(minSoFar))
353
- }
353
+ }
354
+
355
+ /* *
356
+ * 1143. Longest Common Subsequence
357
+ */
358
+
359
+ fun longestCommonSubsequence (text1 : String , text2 : String ): Int {
360
+ val n = text1.length
361
+ val m = text2.length
362
+ val dp = Array (n + 1 ) { IntArray (m + 1 ) }
363
+
364
+ for (i in 1 .. n) {
365
+ for (j in 1 .. m) {
366
+ if (text1[i - 1 ] == text2[j - 1 ]) {
367
+ dp[i][j] = dp[i - 1 ][j - 1 ] + 1
368
+ } else {
369
+ dp[i][j] = maxOf(dp[i][j - 1 ], dp[i - 1 ][j])
370
+ }
371
+ }
372
+ }
373
+
374
+ return dp[n][m]
375
+ }
376
+
377
+ /* *
378
+ * 1048. Longest String Chain
379
+ */
380
+
381
+ fun longestStrChain (words : Array <String >): Int {
382
+ val sortedWords = words.sortedBy { it.length }
383
+ val dp = mutableMapOf<String , Int >()
384
+ var longestChain = 0
385
+
386
+ for (word in sortedWords) {
387
+ var currentChain = 1
388
+ for (i in word.indices) {
389
+ val predecessor = word.removeRange(i, i + 1 )
390
+ currentChain = maxOf(currentChain, dp.getOrDefault(predecessor, 0 ) + 1 )
391
+ }
392
+ dp[word] = currentChain
393
+ longestChain = maxOf(longestChain, currentChain)
394
+ }
395
+
396
+ return longestChain
397
+ }
398
+
399
+ /* *
400
+ * 1027. Longest Arithmetic Subsequence
401
+ */
402
+
403
+ fun longestArithSeqLength (nums : IntArray ): Int {
404
+ val n = nums.size
405
+
406
+ val dp = Array (n) { mutableMapOf<Int , Int >() }
407
+ var longest = 2
408
+
409
+ for (i in 1 until n) {
410
+ for (j in 0 until i) {
411
+ val diff = nums[i] - nums[j]
412
+ val length = dp[j].getOrDefault(diff, 1 ) + 1
413
+ dp[i][diff] = length
414
+ longest = maxOf(longest, length)
415
+ }
416
+ }
417
+
418
+ return longest
419
+ }
0 commit comments