GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javascript.info — A maximal subarray back to the lesson A maximal subarrayimportance: 2 The input is an array of numbers, e.g. The task is: find the contiguous subarray of Write the function For instance:
If all items are negative, it means that we take none (the subarray is empty), so the sum is zero:
Please try to think of a fast solution: O(n2) or even O(n) if you can. Slow solutionWe can calculate all possible subsums. The simplest way is to take every element and calculate sums of all subarrays starting from it. For instance, for
The code is actually a nested loop: the external loop over array elements, and the internal counts subsums starting with the current element.
The solution has a time complexity of O(n2). In other words, if we increase the array size 2 times, the algorithm will work 4 times longer. For big arrays (1000, 10000 or more items) such algorithms can lead to serious sluggishness. Fast solutionLet’s walk the array and keep the current partial sum of elements in the variable If the description is too vague, please see the code, it’s short enough:
The algorithm requires exactly 1 array pass, so the time complexity is O(n). You can find more detailed information about the algorithm here: Maximum subarray problem. If it’s still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that’s better than any words. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |