Java实现《算法导论》最大子数组问题

算法导论第四章分治策略38页最大子数组问题Java实现,算法见书中


public class Main {
	static class Result {
		public int left;
		public int right;
		public int maxSum;

		public Result(int left, int right, int maxSum) {
			this.left = left;
			this.right = right;
			this.maxSum = maxSum;
		}
	}

	public static Result findMaxAcross(int[] arr, int mid, int left, int right,
			Result result) {
		int leftSum = Integer.MIN_VALUE;
		int sum1 = 0;
		for (int i = mid; i >= left; i--) {
			sum1 += arr[i];
			if (sum1 > leftSum) {
				leftSum = sum1;
				result.left = i;
			}
		}
		int rightSum = Integer.MIN_VALUE;
		int sum2 = 0;
		for (int i = mid + 1; i <= right; i++) {
			sum2 += arr[i];
			if (sum2 > rightSum) {
				rightSum = sum2;
				result.right = i;
			}
		}
		result.maxSum = leftSum + rightSum;
		return result;
	}

	public static Result findMaxSumArray(int[] arr, int left, int right,
			Result result) {
		if (left >= right) {
			return result;
		} else {
			int mid = (left + right) / 2;
			Result result1 = findMaxSumArray(arr, left, mid, result);
			Result result2 = findMaxSumArray(arr, mid + 1, right, result);
			Result result3 = findMaxAcross(arr, mid, left, right, result);
			if (result1.maxSum > result2.maxSum
					&& result1.maxSum > result3.maxSum) {
				return result1;
			} else if (result2.maxSum > result1.maxSum
					&& result2.maxSum > result3.maxSum) {
				return result2;
			} else {
				return result3;
			}
		}
	}

	public static void main(String[] args) {
		int[] test = new int[] { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12,
				-5, -22, 15, -4, 7 };
		Result result = new Result(Integer.MIN_VALUE, Integer.MIN_VALUE,
				Integer.MIN_VALUE);
		findMaxSumArray(test, 0, test.length - 1, result);
		System.out.println("result.maxSum = " + result.maxSum
				+ "result.left = " + result.left + "result.right = "
				+ result.right);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值