Problem solving

Maximum subarray sum of three numbers

Dew
1 min readOct 8, 2023

To find the maximum subarray sum of 3 numbers in an array, you can use a simple approach of iterating through the array and considering all possible contiguous subarrays of length 3. Here’s how you can do it in Kotlin:

fun main() {
val nums = intArrayOf(2, -1, 3, 4, -2, 1)
val maxSum = maxSubarraySumOfThree(nums)
println("Maximum subarray sum of 3 numbers: $maxSum")
}

fun maxSubarraySumOfThree(nums: IntArray): Int {
if (nums.size < 3) {
throw IllegalArgumentException("The input array must have at least 3 elements.")
}

var maxSum = Int.MIN_VALUE

for (i in 0 until nums.size - 2) {
val currentSum = nums[i] + nums[i + 1] + nums[i + 2]
if (currentSum > maxSum) {
maxSum = currentSum
}
}

return maxSum
}

This function takes an array of integers as input, checks if it has at least 3 elements, and then iterates through the array, considering all contiguous subarrays of length 3. It calculates the sum of each subarray and keeps track of the maximum sum encountered. Finally, it returns the maximum sum found among all the subarrays.

TIP : This approach finds the maximum subarray sum of 3 or any numbers by iterating through the array once, making it efficient for small subarrays. If you need to find the maximum sum of longer subarrays, you can consider more efficient algorithms like Kadane’s algorithm for larger arrays.

--

--

Dew

Passionate Android developer with a deep interest in crafting elegant and efficient mobile applications. https://letmedo.in/