您的位置:首页 > 其它

[leetcode]53. Maximum Subarray

2017-03-24 13:29 351 查看
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
.

经典的动态规划问题。要求找出最大和的子串。定义两个变量res和sum,ress 是最终要返回的结果。每遍历一个数字num,比较sum + num和num中的较大值存入sum,然后再把res和sum中的较大值存入res,以此类推直到遍历完整个数组,。时间复杂度O(n)

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