Linear-time algorithm for the maximum-subarray problem Java implementation

maximum-subarray problem可以用divide-and-conquer的算法求解,算法复杂度为O(nlgn),另外,还有一种更简单的复杂度为O(n)的方法:


该解法的思路就来自于:《Introduction to Algorithms》中练习:4.1-5:

Use the following ideas to develop a nonrecursive, linear-time algorithm for the maximum-subarray problem. Start at the left end of the array, and progress toward
the right, keeping track of the maximum subarray seen so far. Knowing a maximum subarray of A[1..j] , extend the answer to find a maximum subarray ending at index j+1 by using the following observation: a maximum subarray of A[1.. j+1] is either a maximum subarray of A[1 .. j] or a subarray A[i .. j + 1], for some 1 <=i <=j + 1. Determine a maximum subarray of the form A[i .. j + 1] in constant time based on knowing a maximum subarray ending at index j .


public class MaximumSubArray {
	void maxSubArray(int a[]) {
		int max_so_far = a[0];
	      int max_ending_here = a[0];

		int max_start_index = -1;
		int max_end_index = 0;

		for (int i = 1; i < a.length; i++) {
			max_ending_here = max_ending_here + a[i];
			if (max_ending_here < 0) {
				max_ending_here = 0;
				max_start_index = i;
			} else if (max_so_far < max_ending_here) {
				max_so_far = max_ending_here;
				max_end_index = i;
			}

		}

		if (max_so_far > 0)
			System.out.println("The maximun sub array - size:" + max_so_far + ", from:" + max_start_index + " to:"
					+ max_end_index);
		else
			System.out.println("All negative or zero, the maximum element is:" + max_so_far);
	}

	public static void main(String[] args) {
//		int a[] = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 };
		// int a[] = { -1, -5, -4, -11, -21, -3 };
//		 int a[] = {0, 0, 0, 0, 0};
		int a[] = {1, 2, -1, 3, 4};
		MaximumSubArray ist = new MaximumSubArray();
		ist.maxSubArray(a);
	}
}

注意事项:

上面的代码先给max_so_far,max_ending_here赋了值,然后从index:1开始for循环,这样做的目的就是为了处理数组中都为负数或0的情况。


参考:

http://www.geeksforgeeks.org/archives/576


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值