Created
May 15, 2017 20:13
-
-
Save stahnni/117d2d94ae52f43909a5af44df7603c0 to your computer and use it in GitHub Desktop.
A maximal subarray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The input is an array of numbers, e.g. arr = [1, -2, 3, 4, -9, 6]. | |
The task is: find the contiguous subarray of arr with the maximal sum of items. | |
Write the function getMaxSubSum(arr) that will find return that sum. | |
For instance: | |
getMaxSubSum([-1, 2, 3, -9]) = 5 (the sum of highlighted items) | |
getMaxSubSum([2, -1, 2, 3, -9]) = 6 | |
getMaxSubSum([-1, 2, 3, -9, 11]) = 11 | |
getMaxSubSum([-2, -1, 1, 2]) = 3 | |
getMaxSubSum([100, -9, 2, -3, 5]) = 100 | |
getMaxSubSum([1, 2, 3]) = 6 (take all) | |
If all items are negative, it means that we take none (the subarray is empty), so the sum is zero: | |
getMaxSubSum([-1, -2, -3]) = 0 | |
Please try to think of a fast solution: O(n2) or even O(n) if you can. | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment