[toc]
53 数组最大子数组之和
- 非动规
int max=nums[0];
int sum=0;
for(int i=0;i<nums.length;i++){
sum+=nums[i];
if(max<sum)max=sum;
if(sum<0) sum=0;
}
return max;
- 动规
int[] dp = new int[n];//dp[i] means the maximum subarray ending with A[i];
dp[0] = A[0];
int max = dp[0];
for(int i = 1; i < n; i++){
dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
max = Math.max(max, dp[i]);
}
发表回复