标签: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
.
题目: 找出整数数组中连续的和最大的那个数。
从头开始计算,遇到有和小于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
原文地址:http://blog.csdn.net/laozhaokun/article/details/38390805