diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index a4267a3..af12c6c 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,7 +1,7 @@ package com.github.contest -import com.github.contest.math.closestPrimes +import com.github.contest.dp.longestSubsequence import java.util.TreeMap @@ -11,7 +11,7 @@ import java.util.TreeMap fun main() { - closestPrimes(19, 31).also { it.printArray() } + longestSubsequence(intArrayOf(2, -6, -3, -6, 2, 0), -2).also { println(it) } } fun generateTesting() { diff --git a/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt b/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt index 391c97a..e13fab9 100644 --- a/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt +++ b/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt @@ -454,4 +454,94 @@ fun longestMountain(arr: IntArray): Int { return longestMountain } +/** + * 1493. Longest Subarray of 1's After Deleting One Element + */ + +fun longestSubArray(nums: IntArray): Int { + var left = 0 + var zeroCount = 0 + var maxLen = 0 + + for (right in nums.indices) { + if (nums[right] == 0) { + zeroCount++ + } + + while (zeroCount > 1) { + if (nums[left] == 0) { + zeroCount-- + } + left++ + } + + maxLen = maxOf(maxLen, right - left) + } + + return maxLen +} + +/** + * 2771. Longest Non-decreasing Subarray From Two Arrays + */ + + +fun maxNonDecreasingLength(nums1: IntArray, nums2: IntArray): Int { + val n = nums1.size + // dp1[i]: Length of the longest non-decreasing subarray ending at index i, choosing nums1[i] + // dp2[i]: Length of the longest non-decreasing subarray ending at index i, choosing nums2[i] + val dp1 = IntArray(n) { 1 } + val dp2 = IntArray(n) { 1 } + var maxLen = 1 + + for (i in 1 until n) { + // Case 1: Extending from nums1[i-1] to nums1[i] + if (nums1[i] >= nums1[i - 1]) { + dp1[i] = dp1[i - 1] + 1 + } + + // Case 2: Extending from nums2[i-1] to nums1[i] + if (nums1[i] >= nums2[i - 1]) { + dp1[i] = maxOf(dp1[i], dp2[i - 1] + 1) + } + + // Case 3: Extending from nums2[i-1] to nums2[i] + if (nums2[i] >= nums2[i - 1]) { + dp2[i] = dp2[i - 1] + 1 + } + + // Case 4: Extending from nums1[i-1] to nums2[i] + if (nums2[i] >= nums1[i - 1]) { + dp2[i] = maxOf(dp2[i], dp1[i - 1] + 1) + } + + // Update the overall maximum length + maxLen = maxOf(maxLen, maxOf(dp1[i], dp2[i])) + } + + return maxLen +} + +/** + * 1218. Longest Arithmetic Subsequence of Given Difference + */ + + +fun longestSubsequence(arr: IntArray, difference: Int): Int { + val dp = mutableMapOf() + var maxLen = 0 + + for (num in arr) { + val prev = num - difference + val len = dp.getOrDefault(prev, 0) + 1 + dp[num] = len + maxLen = maxOf(maxLen, len) + } + + return maxLen +} + + + +