您的位置:首页 > 编程语言 > Java开发

Leetcode 53. Maximum SubarrayJAVA语言

2017-03-11 20:06 387 查看
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.
题意:求连续子数组的最大和
public class Solution {
public int maxSubArray(int[] nums) {
int len=nums.length;
if(nums==null || len==0)return 0;
int MAX=nums[0];
int curSum=nums[0];
for(int i=1;i<len;i++){
if(curSum>0){
curSum+=nums[i];
}else{
curSum=nums[i];
}
MAX=Math.max(curSum,MAX);
}
return MAX;

}
}
PS:第一种思路,逐渐累加循环。
还有一种思路,可以用动态规划做。
public class Solution {
public int maxSubArray(int[] nums) {
int len=nums.length;
if(nums==null || len==0)return 0;
//dp[i]代表以nums[i]为结尾的最大和。
int[] dp=new int[len];
dp[0]=nums[0];
int MAX=dp[0];
for(int i=1;i<len;i++){
if(dp[i-1]<0){
dp[i]=nums[i];
}else{
dp[i]=dp[i-1]+nums[i];
}
MAX=Math.max(dp[i],MAX);
}
return MAX;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  子数组 连续 最大和