第四章 分治策略 练习4.1-5
使用如下思想为最大子数组问题设计一个非递归的、线性时间的算法。从数组的左边界开始,由左往右处理,记录到目前为止已经处理过的最大子数组。若已知A[1...j]
的最大子数组,基于如下性质将解扩展为A[1...j+1]
的最大子数组:A[1...j+1]
的最大子数组要么是A[1...j]
的最大子数组,要么是某个子数组A[i...j+1]
(1<= i <= j+1)。在已知A[1...j]
的最大子数组的情况下,可以在线性时间内找出开始A[i...j+1]
的最大子数组。
基于java的实现方法如下:
/**
* 最大子数组
* Created by Sherlock on 2016/2/26.
*/
public class MaxSubArray<T extends Comparable<T>> {
private List<T> list = new ArrayList<>();
private final Addition<T> addition;
public MaxSubArray(List<T> list, Addition<T> addition){
this.list.addAll(list);
this.addition = addition;
}
/**
* @param zero 零值,用于比较
* @return 返回 最大子数组
*/
public List<T> findMaxSubArray(T zero){
//初始A[i...j+1] = A[0]
T frontierSum = list.get(0);
int frontierL = 0;//记录始坐标
int frontierR = 0;//记录末坐标
T maxSubSum = list.get(0);
int left = 0;//记录始坐标
int right = 0;//记录末坐标
for (int i = 1; i < list.size(); i++){
//如果前面的A[i...j+1]<=0,直接弃用,更新为最新值
if (frontierSum.compareTo(zero) <= 0){
frontierSum = list.get(i);
frontierL = i;
frontierR = i;
}else{
//累加,并更新末坐标
frontierSum = addition.add(frontierSum,list.get(i));
frontierR = i;
}
//比较最大子数组的和与A[i...j+1]的和的大小,如果小于A[i...j+1],则更新当前i的最大子数组并记录坐标
if (maxSubSum.compareTo(frontierSum) < 0){
maxSubSum = frontierSum;
left = frontierL;
right = frontierR;
}
}
//返回最大子数组subList(fromIndex,toIndex)是[fromIndex,toIndex)取值的,所以这里加1
return list.subList(left,right+1);
}
//实现加法运算
public interface Addition<T> {
T add(T t1, T t2);
}
}
测试代码如下:
public class Main {
public static void main(String[] args) {
maxSubArray(0);
}
private static void maxSubArray(int zero){
int[] numbers = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -22, 15, -4, 7};
List<Integer> data = new ArrayList<>();
for (int i = 0; i < numbers.length; i++){
data.add(i,numbers[i]);
}
MaxSubArray<Integer> list = new MaxSubArray<>(data, new MaxSubArray.Addition<Integer>() {
@Override
public Integer add(Integer t1, Integer t2) {
return t1 + t2;
}
});
data = list.findMaxSubArray(zero);
System.out.println("最大子数组如下");
int sum = 0;
for (int i : data){
System.out.print(i+" ");
sum += i;
}
System.out.println("\n其和为:"+sum);
}
}
运行测试代码,结果如下:
最大子数组如下
18 20 -7 12
其和为:43