Skip to content

Commit d3dba64

Browse files
add 2771
1 parent 5750aa4 commit d3dba64

File tree

2 files changed

+73
-2
lines changed

2 files changed

+73
-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.math.closestPrimes
4+
import com.github.contest.dp.maxNonDecreasingLength
55
import java.util.TreeMap
66

77

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

1212
fun main() {
1313

14-
closestPrimes(19, 31).also { it.printArray() }
14+
maxNonDecreasingLength(intArrayOf(11, 7, 7, 9), intArrayOf(19, 19, 1, 7))
1515
}
1616

1717
fun generateTesting() {

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

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,4 +454,75 @@ fun longestMountain(arr: IntArray): Int {
454454
return longestMountain
455455
}
456456

457+
/**
458+
*
459+
*/
460+
461+
fun longestSubArray(nums: IntArray): Int {
462+
var left = 0
463+
var zeroCount = 0
464+
var maxLen = 0
465+
466+
for (right in nums.indices) {
467+
if (nums[right] == 0) {
468+
zeroCount++
469+
}
470+
471+
while (zeroCount > 1) {
472+
if (nums[left] == 0) {
473+
zeroCount--
474+
}
475+
left++
476+
}
477+
478+
maxLen = maxOf(maxLen, right - left)
479+
}
480+
481+
return maxLen
482+
}
483+
484+
/**
485+
* 2771. Longest Non-decreasing Subarray From Two Arrays
486+
*/
487+
488+
489+
fun maxNonDecreasingLength(nums1: IntArray, nums2: IntArray): Int {
490+
val n = nums1.size
491+
// dp1[i]: Length of the longest non-decreasing subarray ending at index i, choosing nums1[i]
492+
// dp2[i]: Length of the longest non-decreasing subarray ending at index i, choosing nums2[i]
493+
val dp1 = IntArray(n) { 1 }
494+
val dp2 = IntArray(n) { 1 }
495+
var maxLen = 1
496+
497+
for (i in 1 until n) {
498+
// Case 1: Extending from nums1[i-1] to nums1[i]
499+
if (nums1[i] >= nums1[i - 1]) {
500+
dp1[i] = dp1[i - 1] + 1
501+
}
502+
503+
// Case 2: Extending from nums2[i-1] to nums1[i]
504+
if (nums1[i] >= nums2[i - 1]) {
505+
dp1[i] = maxOf(dp1[i], dp2[i - 1] + 1)
506+
}
507+
508+
// Case 3: Extending from nums2[i-1] to nums2[i]
509+
if (nums2[i] >= nums2[i - 1]) {
510+
dp2[i] = dp2[i - 1] + 1
511+
}
512+
513+
// Case 4: Extending from nums1[i-1] to nums2[i]
514+
if (nums2[i] >= nums1[i - 1]) {
515+
dp2[i] = maxOf(dp2[i], dp1[i - 1] + 1)
516+
}
517+
518+
// Update the overall maximum length
519+
maxLen = maxOf(maxLen, maxOf(dp1[i], dp2[i]))
520+
}
521+
522+
return maxLen
523+
}
524+
525+
526+
527+
457528

0 commit comments

Comments
 (0)