Max Sum Subarray Kotlin Function Explained
Q: Implement a Kotlin function to find the maximum sum of a subarray within a given array.
- Kotlin
- Senior level question
Explore all the latest Kotlin interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Kotlin interview for FREE!
fun findMaxSubarraySum(array: IntArray): Int { var maxSum = array[0] var currentSum = array[0] for (i in 1 until array.size) { currentSum = maxOf(array[i], currentSum + array[i]) maxSum = maxOf(maxSum, currentSum) } return maxSum }
Explanation:
The findMaxSubarraySum function takes an integer array array as input and returns the maximum sum of a subarray within the array.
It initializes maxSum and currentSum to the first element of the array.
It iterates through the array starting from the second element using a for loop.
For each element, it compares the value of the element with the sum of the current element and the previous sum (currentSum + array[i]). It chooses the maximum value between the two.
The currentSum represents the sum of the subarray ending at the current index.
The maxSum keeps track of the maximum sum encountered so far.
After iterating through all elements, it returns the maxSum, which represents the maximum sum of a subarray within the array.


