首页 > 其他 > 详细

LeetCode——Maximum Subarray

时间:2014-08-05 22:37:50      阅读:362      评论:0      收藏:0      [点我收藏+]

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.

原题链接: https://oj.leetcode.com/problems/maximum-subarray/

题目: 找出整数数组中连续的和最大的那个数。

从头开始计算,遇到有和小于0的,则忽略前面的和,往前计算。

	public static int maxSubArray(int[] A) {
		int sum = 0;
		int maxSum = Integer.MIN_VALUE;
		for (int i = 0; i < A.length; i++) {
			sum += A[i];
			if (sum < 0)
				sum = 0;
			maxSum = Math.max(maxSum, sum);
		}
		return maxSum;
	}


动态规划的方法。

	public static int maxSubArray(int[] A) {
		int max = A[0];
		int sum[] = new int[A.length];
		sum[0] = A[0];
		for (int i = 1; i < A.length; i++) {
			sum[i] = Math.max(A[i], sum[i - 1] + A[i]);
			max = Math.max(max, sum[i]);
		}
		return max;
	}


LeetCode——Maximum Subarray,布布扣,bubuko.com

LeetCode——Maximum Subarray

原文:http://blog.csdn.net/laozhaokun/article/details/38390805

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!