Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sliding-window-algorithm-technique: examples (kotlin)
// see: https://itnext.io/sliding-window-algorithm-technique-6001d5fbe8b3
fun main() {
intro()
`Maximum sum subarray of Size k`()
//`Count Occurrences of Anagram`()
}
fun intro() {
listOf("a", "b", "c", "d", "e", "f", "g", "h")
.windowed(size = 3, step = 1, partialWindows = false) { currentWindow: List<String> ->
println("currentWindow: $currentWindow")
currentWindow
}
}
fun `Maximum sum subarray of Size k`() {
val slidingSums: List<Int> = listOf(3, 5, 2, 1, 7)
.windowed(size = 2, step = 1, partialWindows = false) { currentWindow: List<Int> ->
println("currentWindow: $currentWindow -> sum() ${currentWindow.sum()}")
currentWindow.sum()
}
val maxSum: Int? = slidingSums.maxOrNull()
println("Maximum sum subarray of Size k=2: $maxSum")
}
fun `Count Occurrences of Anagram`() {
val text = "gotxxotgxdogt"
val word = "got"
TODO()
}
private fun isAnagram(s1: String, s2: String): Boolean {
// Explanation: Words — got, otg, ogt are anagrams of got.
if (s1.length != s2.length) {
return false
}
val c1: CharArray = s1.toCharArray()
val c2: CharArray = s2.toCharArray()
return c1.sorted() == c2.sorted()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment