Skip to content

Commit cc2a0c0

Browse files
add 2760 alt sol
1 parent 54d091b commit cc2a0c0

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowAlternativeSolution.kt

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,32 @@ fun minWindowOptimumSolution(s: String, t: String): String {
4949
}
5050

5151
return if (minLength == Int.MAX_VALUE) "" else s.substring(minStart, minStart + minLength)
52+
}
53+
54+
/**
55+
* 2760. Longest Even Odd Subarray With Threshold
56+
* Alternative Solution with O(n) Time Complexity
57+
*/
58+
59+
fun longestAlternatingSubArrayAlternativeSolution(nums: IntArray, threshold: Int): Int {
60+
var maxLength = 0
61+
var currentLength = 0
62+
63+
for (i in nums.indices) {
64+
65+
if (nums[i] <= threshold &&
66+
(currentLength == 0 && isEven(nums[i]) || currentLength > 0 && nums[i] % 2 != nums[i - 1] % 2)
67+
) {
68+
currentLength++
69+
maxLength = maxOf(maxLength, currentLength)
70+
} else currentLength = if (nums[i] % 2 == 0 && nums[i] <= threshold) 1 else 0
71+
72+
}
73+
74+
return maxLength
75+
}
76+
77+
private fun isEven(number: Int) = when {
78+
number % 2 == 0 -> true
79+
else -> false
5280
}

0 commit comments

Comments
 (0)