您的位置:首页 > 其它

LeetCode-53-Maximum Subarray

2016-06-22 23:28 330 查看
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
.

题意:就是求最大字数组和。

思路:

  DP问题,O(n)内可破

  对于位置arr[0]~arr[i],最大字数组和

          arr[0] i==0

  maxSum[i]=

          max{ maxSum[i-1]+arr[i] , arr[i] } 0<i<arr.length

  具体来说该题没必要采用maxSum数组,用一个变量记住最大字数组和即可。

Java代码如下:

public class Solution {
public int maxSubArray(int[] nums) {
int max = nums[0],maxEndingHere = nums[0];
for (int i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(maxEndingHere+nums[i],nums[i]);
max = Math.max(maxEndingHere,max);
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: