连续最大和自数组

题目:

/**
 * Find the contiguous subarray within an array (containing at least one number)
 * which has the largest sum. For example, given the array [-2, 1, -3, 4, -1,
 * 2,1, -5, 4 ], the contiguous subarray [4,-1,2,1] has the largest sum = 6.
 * 
 * More practice:
 * 
 * If you have figured out the O(n) solution, try coding another solution using
 * the divide and conquer approach, which is more subtle.
 * 
 */


public class MaximumSubarray {
	public static void main(String[] args) {
		int[] input = { -2, 1, -3, 4, -1, 2, 1, -5, 110 };
		MaximumSubarray ms = new MaximumSubarray();
		int[] out = ms.solution(input);
		System.out.println(Arrays.toString(out));
	}
	// o(n)方法 , 另一种应该可以 但是目前还没想出来
	public int[] solution(int[] input) {

		int length = input.length;
		int index = 0;

		int sum = 0;	   				// 临时和
		int maxsum = 0;					// sub array 最大和

		int start = 0;					// sub array 开始
		int end = 0;					// sub array 结束

		int start_tmp = 0;				// 临时开始	

		while (input[index] < 0) {		// 从正的开始
			index++;
		}

		for (int i = index; i < length; i++) {
			sum = sum + input[i];
			if (sum > maxsum) {
				maxsum = sum;				// 当前和比maxsum 大 , 则maxsum至为当前和, 且end 至为 i
				end = i;
				start = start_tmp;			// start 变成 start_tmp
			}
			if (sum < 0) {					//只要前面的不为负 , 则一定要加上前面的, 为负数了, 就 sum 至0, 往后看
				sum = 0;					
				start_tmp = i + 1;			// 表示 此时的和 是从这里开始加的
			}

		}

		int[] result = new int[end - start + 1];
		System.arraycopy(input, start, result, 0, end - start + 1);
		System.out.println(maxsum);
		return result;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值