一维数组及子数组最大和问题Java实现

一维数组及子数组最大和问题,比如数组int[] source = new int[]{1,-2,3,4,6}的子数组的组合最大和是3,4,6的组合13,其他的组合都比这个小;

刚开始是用一种暴力的算法,但是这种算法时间复杂度很高O(n3);就是每个组合的值都算一遍,然后找到最大的;

第二种算法我忘记了,之后补上;

第三种算法的思想是,如果以i为结尾的数组组合的最大值为负数,那么后面的组合值就没有必要加上之前的数组了;

package design;

public class TheMaxOfArray {

	/**
	 * @param source
	 *            数组
	 * @param i
	 *            开始节点
	 * @param j
	 *            结束节点
	 * @return 开始节点至结束节点的和
	 * @throws Exception
	 */
	public static int getSumFromArray(int source[], int i, int j)
			throws Exception {
		if (source == null) {
			throw new RuntimeException("输入数组为空!");
		}
		if (source.length == 0) {
			throw new Exception("输入的数组没有内容让我怎么算啊?");
		}
		if (i > j) {
			throw new Exception("数组开始节点比结束节点大!");
		}
		if (i > source.length || j > source.length) {
			throw new Exception("数组越界!");
		}
		int result = 0;
		for (int n = i; n <= j; n++) {
			result += source[n];
		}
		return result;
	}

	/**
	 * @param source
	 * @return 第一种解法,时间复杂度O(n3)
	 * @throws Exception
	 */
	public static int findMaxFirst(int source[]) throws Exception {
		if (source == null) {
			throw new RuntimeException("输入数组为空!");
		}
		if (source.length == 0) {
			throw new Exception("输入的数组没有内容让我怎么算啊?");
		}
		int max = source[0];
		int length = source.length;

		/** 暴力解法,i是开始节点,j是结束节点 */
		for (int i = 0; i < length; i++) {
			for (int j = i; j < length; j++) {
				int tempResult = getSumFromArray(source, i, j);
				max = max > tempResult ? max : tempResult;
			}
		}
		return max;
	}

	/**
	 * @param source
	 * @return O(n)时间复杂度的算法
	 * @throws Exception
	 */
	public static int findMaxFinal(int source[]) throws Exception {
		if (source == null) {
			throw new RuntimeException("输入数组为空!");
		}
		if (source.length == 0) {
			throw new Exception("输入的数组没有内容让我怎么算啊?");
		}
		/**
		 * 设置Max为最大数值,temp为每次以source[i]为结尾的数组的最大值,如果temp为负,则之后的组合不必加上temp,如果为正,
		 * 则之后的数组组合需要加上temp 这种算法的时间复杂度是O(n),空间复杂度是O(1);
		 */
		int max = source[0];
		int temp = max;
		int length = source.length;
		for (int i = 1; i < length; i++) {
			if (temp > 0) {
				temp += source[i];
			} else {
				temp = source[i];
			}
			max = max > temp ? max : temp;
		}
		return max;
	}

	public static void main(String args[]) throws Exception {
		int[] testSource = new int[] { 1, -2, 5, -3, 10 };
		System.out.println(findMaxFirst(testSource));
		System.out.println(findMaxFinal(testSource));
	}
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值