Overview
This class completed the treatment of the maximum subarray problem: after a brief revision of quicksort (median-of-3 pivot selection and its 14 percent reduction in computational requirement) and the key differences between quicksort and merge sort, the session motivated the maximum subarray problem from a stock-market scenario, derived the brute-force solution (order of n square, order of n cube if ordered subsets are considered), and developed the divide-and-conquer solution via left sum, right sum and cross sum. A full divide-and-conquer trace was worked on a 16-element array, then re-examined to clarify how the cross sum is bounded by the extreme indices of the left and right sums, and finally walked through on a smaller 8-element array. The class sits in the divide-and-conquer portion of the course, with Kadane's algorithm and the dynamic-programming treatment explicitly deferred.
Learning outcomes
- Explain median-of-3 pivot selection in quicksort and why it improves behaviour on nearly sorted input.
- Contrast quicksort and merge sort on in-place operation, extra memory, cache friendliness and memory operations.
- State the maximum subarray problem and its stock-market motivation, including the all-positive and all-negative edge cases.
- Write the brute-force solution and justify its order of n square complexity (order of n cube if ordered subsets are counted).
- Apply divide and conquer to maximum subarray: compute left sum, right sum and cross sum, and propagate results upward.
- Bound the cross sum correctly between the extreme indices of the left sum and the right sum.
- Explain why the median convention (n/2 vs n/2+1) must be applied consistently at all recursion levels.
Core concepts
Median of 3 (quicksort pivot selection)
The three elements considered are the first, middle and last element; they are arranged so that the required order (first should be less than ...) is followed. It matters because it prevents worst-case behaviour in a nearly sorted array and helps maintain nearly equal partitions, reducing the computational requirement by 14 percent. It connects to the recurrence t(n) = 2t(n/2) + order of n, which gives n log n only for balanced partitions.
In-place operation and cache friendliness (quicksort vs merge sort)
In quicksort the same memory location is used; merge sort requires extra memory and stores the result at a different place. Quicksort is cache friendly; merge sort has more memory operations. Cache friendly means no extra space is primarily required. This connects to the practical comparison of the two sorting algorithms revised at the start of class.
Maximum subarray problem
Given an array containing both positive and negative numbers, identify a subarray whose sum is highest. It is inspired by a real-world stock-market scenario: buy a share on a certain day and sell it after some day (the share remains blocked for some days); if you enter on a day when the price is very low and sell on a day when the price is very high, the profit margin becomes maximum. It is called a "problem" because it is a task posed in practical scenarios (e.g., share trading, maximum quarterly earnings), like sorting or searching problems. It is the running example for the divide-and-conquer technique.
All-positive / all-negative cases
If all elements are positive, the sum of all elements is the maximum sum. If all are negative, pick the least negative single number. The problem is really interesting when the array contains both positive and negative numbers.
Brute force (maximum subarray)
Check all possibilities and identify whichever is highest. When taking values a and b, the pair b, a is not taken as a subset — order is not bothered about because the sum remains the same. This wisely removes duplicate entries/subsets and reduces complexity from order of n cube to order of n square; if order were considered (a, b and also b, a), complexity reaches order of n cube. The laptop analogy: brute force searches every space in the house, garden, washroom, etc.; applying a little heuristic/intelligence restricts the search to the living area, study and bedroom, raising the chance of finding it and removing irrelevant work.
Divide and conquer
Divide, conquer, combine. Partition the array, solve on the left and right, and stop the recursive division when a single-element level is reached. The formal algorithm will be seen at the later stage.
Left sum, right sum, cross sum
Left sum: adding the entries of the left side and picking out the maximum. Right sum: similarly, pick the max on the right side. Cross sum: identify the middle (median) part; from the median go toward the left and identify the maximum possible sum, from the median go toward the right and identify the maximum sum, then add them. Cross sum does not mean taking all entries of the left side and all entries of the right side and adding them. The maximum subarray may reside on the left part, the right part, or the cross section.
Bounding the cross sum
The cross sum is computed only between the index where the left-side maximum was found and the index where the right-side maximum was found; going beyond that gives no significant difference and defeats the purpose of the algorithm. This is "not an assumption, this is the algorithm part." Indices are tracked so that at the top level the algorithm knows to what extent it must take values and find the sum.
Propagation across recursion levels
The cross sum computed for a subproblem becomes the left sum (or right sum) for the larger array at the level above: "a cross sum becomes a left sum when we proceed upward." The highest cross sum at a level becomes the left sum for the level above.
Median consistency
Whichever median convention is used (n/2 or n/2+1) must be used consistently at all levels; changing it midway gives a different intermediate result. The claim made is that the final answer (e.g., 25) is the same either way, but this was to be verified by solving a problem with n/2+1 as median.
Dynamic programming (mentioned)
All dynamic programming algorithms fasten processing by taking extra space; previous results are stored and used to get the next step result. In divide and conquer the stored values are only temporary, not fixed/preserved for the entire process.
Formulas and maths
- (t(n) = 2t(n/2) + O(n)) Symbols: t(n) is the running time on n elements; the two recursive calls are on halves; O(n) is the partitioning cost. Used for balanced partitioning in quicksort — only in this case is the complexity n log n; otherwise it may reach n square when the array is already sorted.
- Median of 3 reduces the computational requirement by 14 percent. Symbols: 14 percent is the reduction in computational requirement from median-of-3 pivot selection. Used when arguing the practical benefit of median-of-3 over a naive pivot.
- Brute force: loop i = 1 to n, inner loop j = 1 to n; sum = sum + a[j] (as transcribed: "sum equal to sum of aji"); if sum > max then max = sum. Symbols: i and j are loop indices over the array a; sum accumulates the running subarray sum; max holds the best sum found. Used for the brute-force maximum subarray solution; loop inside loop gives complexity order of n square.
- Number of subarrays checked by brute force: (n(n+1)/2). Symbols: n is the array length; the count is the number of contiguous subarrays (unordered, so a, b and b, a are not counted twice). Used to justify the order of n square complexity of the brute-force maximum subarray solution.
- (mid = (low + high)/2) (as spoken: "int low plus high by 2") Symbols: low and high are the current subarray bounds; mid is the split point. Used in the divide-and-conquer split; the same is applicable for odd-length arrays.
- Cross sum = (maximum sum from median toward left) + (maximum sum from median toward right). Symbols: the two terms are the best sums extending from the midpoint outward on each side. Used to handle the case where the maximum subarray crosses the midpoint.
- Cross sum search range: from the extreme index of the left sum to the extreme index of the right sum (e.g., a[4] to a[11] in the large example; a[1] to a[8] at the top level of the small example). Symbols: the extreme indices mark where the best left and right sums were found. Used to bound the cross-sum computation.
- Algorithm structure as described: "mid down to low" for the left side and "mid plus one ... up to high" for the right side. Symbols: mid, low, high as above. Used when scanning outward from the midpoint to compute the cross sum.
Worked examples
Quicksort on sorted input: standard example 10, 20, 30, 40, 50 — already sorted; number of elements counted as 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Total comparisons required: 45; worst-case behaviour is order of n. With the other strategy the total comparisons required is 39 — 6 less when the number is only 10; when the number is 100 it is 60 less. This shows median of 3 reduces complexity from order of n square toward n log n.
Brute force on 2, −6, −1, 3, −1, 2, 3: - Starting at first element: 2; 2 + (−6) = −4; then −5; then −2; then −1; then −3; then adding last gives −3. Highest sum received here is 2. - Starting at second element (−6): −6, −7, −4, −5, −3, −5; maximum possible sum is −3. - Starting at −1: −1, 3 → 2, then −1 → 1, then 2 → 3, then −2 → 1; maximum value achieved is 3. - Starting at 3: 3, −1 → 2, +2 → 4; here we get 4. - Overall highest: subarray 3, −1, 2 with sum equal to 4.
Brute force loop trace on 2, −6, −1 (six numbers, i = 1): sum = 2; max was 0, so max = 2. j = 2: sum = −4, max stays 2. j = 3: sum = −5, max stays 2. j = 4: sum = −2, max stays 2. j = 5: sum = −4, max stays 2. j = 6: sum = −9, max stays 2. Then i = 2, j runs 2 to 6, and so on.
Divide and conquer trace on 16 elements: 13, −3, −25, 20, −3, −16, −23, 18, 20, −7, 12, −5, −22, 15, −4, 7 (low = index 1, high = index 16). - First split (8 and 8): left = 13, −3, −25, 20, −3, −16, −23, 18; right = 20, −7, 12, −5, −22, 15, −4, 7. - Left half splits into (13, −3, −25, 20) and (−3, −16, −23, 18); then into (13, −3), (−25, 20), (−3, −16), (−23, 18). - (13, −3): left sum 13, right sum −3, cross sum 10 → highest 13 propagates up. - (−25, 20): left sum −25, right sum 20, cross sum −5 → right sum 20 propagates up. - (13, −3, −25, 20): left sum 13, right sum 20; cross sum: from mid leftward max is 10 (−3 and 13), rightward is −5 (−25 and 20), so cross sum = 5; highest is 20 → right sum 20 propagates. - (−3, −16): cross sum −19 → left sum −3 propagates. (−23, 18): cross sum −5 → right sum 18 propagates. - (−3, −16, −23, 18): from mid leftward max is −16 (including −3 makes it more negative); rightward include 18 (−23 + 18 = −5); cross sum = −21 → right sum 18 propagates. - Big left array: left part max 20, right part max 18. Cross sum: going left from the middle, 20, then −25 → −5, then −8, then 13 gives total 33, 5 [unclear] but we bound to 20; going right, we bound to −3 (do not go beyond). Left sum 20, right sum 18 → 20 propagates upward; its index is A of 4. - Right half splits into (20, −7, 12, −5) and (−22, 15, −4, 7); then (20, −7), (12, −5), (−22, 15), (−4, 7). - (20, −7): left 20, right −7, cross 13 → left sum 20. (12, −5): cross 7 → left sum 12. - (20, −7, 12, −5): cross sum = 25 (13 from the left side plus 12, stopping at 12) — highest; subarray from 20 to 12 gives maximum value 25. - (−22, 15): left sum 15 comes up. (−4, 7): right sum 7 comes up. - (−22, 15, −4, 7): going left from mid gets more negative, stop at 15; rightward −4 and 7 = 3; cross sum = 18 → take 18 (from 15, 7 or 18). - Big right array: left sum 25, right sum 18. Going left: +7, 0, 20 — considering all 4 gives sum 20; going right: −22, −4, 26 [unclear], 5 and 7, 22, −4 — considering all 4 is good; cross sum becomes 16 (from the right side: −22 + 15 = −7, −4 → −11, +7 → −4). Cross sum of 25 is around the 20 and −5. - Final cross sum: from the left, adding gives −16, −3, 20 → 1, then −25; beyond 20 we will not go. From the right, −23, 18 → −5 plus 20; beyond 12 we will not get a higher value. The cross sum is computed only over A of 4 to A of 11 (indices 9, 10, 11, 12 on the right side), not beyond.
Large example (revisited): - Array: 13, −3, −25, 20, −3, −16, −23, 18, 20, −7, 12, −5 (note: −5, not −15). - Left sum = 20 at index 4; right sum = 25 from elements 20, −7, 12 at indices 9, 10, 11. - Cross sum range: a[4] to a[11] (not 12). Elements: 20, −3, −16, −23, 18, 20, −7, 12 (8 elements). - From the left side (going left from the median): −23, −16, −3, but 20 is obtained → sum −22 from this side. - From the right end: 18, 20, −7, 12 → sum 43. - Resultant cross sum = 21; since 25 was already achieved, the overall result remains 25.
Small 8-element example: - Array: 20, −7, 12, −5, −22, 15, −4, 7 (indices 1–8). - Split: [20, −7, 12, −5] and [−22, 15, −4, 7]; further splits into pairs. - Pair [20, −7]: left sum 20, right sum −7, cross sum considers both (indices 1 and 2); left sum propagates up as 20. - Pair [12, −5]: left sum 12, right sum −5, cross sum 7; bounding indices 3 and 4; right sum is 12. - Combining [20, −7, 12]: highest values 20 (index 1–2) and 12 (index 3 only, not 4); values 20, −7, 12; left side sum 13, right side sum 12; cross sum 25 → highest is 25; left sum for the bigger array becomes 25, spanning 20 to 12. - Portion [−22, 15]: cross sum −7; left sum becomes 15, index 6. - Portion [−4, 7]: right sum becomes 7, index 8. - Cross sum for indices 6 to 8: values 15, −4, 7 → 11 and 7 → cross sum 18; this becomes the right sum for the level above (18, indices 6–8). - Top-level cross sum: extreme ends 1 to 8; left value 20, right value −4 → cross sum 16. - Candidates: 16, 25, 18 → highest is 25, at indices 1 to 3. Final answer: 25.
Student's alternative attempt (median at 18): - Array: 20, −3, −16, −23, 18, 20, −7, 12. - Taking the median as −23: left maximum would be −23, right maximum 43. - Instructor's response: 18 falls on the right side of the split; the subarrays should be considered accordingly; the median convention (n/2 or n/2+1) must be applied consistently at all lower branches; the same result of 25 should follow.
Questions asked in class
Punit: why not use Kadane's algorithm instead? Maximum sum can be solved via brute force, divide and conquer, and dynamic programming; Kadane's algorithm will be discussed when dynamic programming is covered. Dynamic programming's space complexity is a little higher than divide and conquer, but it is famous for maximum subarray; all dynamic programming algorithms fasten processing by taking extra space — storing previous results in memory and using them to get the next step result. Here also previous results are stored after getting the median, but these are just temporary, not fixed; in dynamic programming