第四章 分治策略
最大子数组问题(分治法)
问题描述:
给出数组A,寻找A的最大的非空连续子数组,其中A不能全为非负数。
问题分析:
1、最简单的方法便是暴力搜索,找到最大的子数组,所需要的时间为Θ(n^2)。
2、使用分治的策略,分治法就是把一个大的问题简化为几个小的问题来进行求解。我们可以把数组A从中点分割成两个子数组L,R;那么最大子数组问题简化为以下三种情况:
- 最大子数组位于L中,
- 最大子数组位于R中,
- 最大子数组跨越中点,一部分在L中,一部分在R中。
那么我们就可以使用递归的方式来进行求解了
伪代码:
FIND_MAX_CROSSING_SUBARRAY(A, low, mid, high):
1 left_sum = INT_MIN
2 sum = 0
3 for i = mid downto low
4 sum = sum + A[i]
5 if sum > left_sum
6 left_sum = sum
7 left_max = i
8 right_sum = INT_MIN
9 sum = 0
10 for i = mid+1 to high
11 sum = sum + A[i]
12 if sum > right_sum
13 right_sum = sum
14 right_max = i
15 return (left_max, right_max, left_sum + right_sum)
//
FIND_MAX_SUBARRAY(A, low, high):
1 if low == high
2 return (low, high, A[low])
3 else
4 mid = (low+high)/2 //向下取整
5 (left_low, left_high, left_sum) = FIND_MAX_SUBARRAY(A, low, mid)
6 (right_low, right_high, right_sum) = FIND_MAX_SUBARRAY(A, mid+1, high)
7 (cross_low, cross_high, cross_sum) = FIND_MAX_CROSSING_SUBARRAY(A, low, mid, high)
8 if left_sum >= right_sum and left_sum >= cross_sum
9 return (left_low, left_high, left_sum)
10 else if right_su