Kotlinlearncs.online LogoJava
Return to List

Solve: 2D Array Max Subarray Sum

Created By: Geoffrey Challen
/ Version: 2021.8.0

Write a function maxSubarraySum that, given a non-rectangular two-dimensional non-nullable Int array, returns the sum of the subarray that sums to the largest value.

So given the following array, with each subarray on a separate line:

1, 2, 4
4, 1, -1
6, 8, -10, -9
-1

You would return 7. The passed array will contain no empty subarrays.

One hint for this problem is that you may need both an Int variable to store the max and a Boolean variable to record whether the maximum value has been initialized. Once you have summed each subarray, check whether either your Boolean value is false or the sum is larger than the largest you've seen so far. After you check the sum of the first subarray, set your Boolean value to true. Another approach is to use the counter that you use to proceed through each subarray to determine whether you have initialized the max value.

Related Lessons

Stuck? You may find these lessons helpful: