码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode——Maximum Subarray

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

标签:leetcode

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

标签:leetcode

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!