Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to find the maximum length of a subarray having a sum equal to K in Kotlin

1 Answer

0 votes
fun maxLengthSubarrayEqualsToK(arr: IntArray, K: Int): Int {
    val map = mutableMapOf<Int, Int>() // To store cumulative sum and its index
    var maxLength = 0
    var cumulativeSum = 0

    for (i in arr.indices) {
        cumulativeSum += arr[i]

        // If the cumulative sum equals K, update maxLength
        if (cumulativeSum == K) {
            maxLength = i + 1
        }

        // If (cumulativeSum - K) exists in the map, update maxLength
        if (map.containsKey(cumulativeSum - K)) {
            val prevIndex = map[cumulativeSum - K]!!
            maxLength = maxOf(maxLength, i - prevIndex)
        }

        // Store the cumulative sum in the map if not already present
        if (!map.containsKey(cumulativeSum)) {
            map[cumulativeSum] = i
        }
    }

    return maxLength
}

fun main() {
    val arr = intArrayOf(1, -1, 5, -2, -3, 2, 3, 3)
    val K = 3

    // 1, -1, 5, -2 = 3 (length 4)
    // 5, -2 = 3 (length 2)
    // -2, -3, 2, 3, 3 = 3 (length 5)

    println(maxLengthSubarrayEqualsToK(arr, K)) 
}




/*
run:

5

*/

 



answered Sep 5, 2025 by avibootz
...