描述
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例
输入:nums = [-2,1,-3,4,-1,2,1,-5,4] 输出:6 解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
Tag
array | divide-and-conquer | dynamic-programming
思路
代码
方法一:暴力求解O(n3)
public int maxSubArray(int[] nums) {
int maxSum =0;
for (int i = 0; i < nums.length; i++) {
for (int j = i; j < nums.length; j++) {
int tempSum=0;
for (int k = i; k <= j; k++) {
tempSum += nums[k];
}
if (tempSum > maxSum) {
maxSum=tempSum;
}
}
}
return maxSum;
}
方法二:暴力求解改进版O(n2)
public int maxSubArray1(int[] nums) {
int maxSum=0;
for (int i = 0; i < nums.length; i++) {
int tempSum=0;
for (int j = i; j < nums.length; j++) {
tempSum += nums[j];
if (tempSum > maxSum) {
maxSum=tempSum;
}
}
}
return maxSum;
}
方法三:O(n)
public int maxSubArray2(int[] nums) {
int maxSum=0;
int tempSum=0;
for (int i = 0; i < nums.length; i++) {
tempSum+=nums[i];
if (tempSum > maxSum) {
maxSum=tempSum;
} else if (tempSum < 0) {
tempSum=nums[i];
}
}
return maxSum;
}
方法四:leetCode题解
public int maxSubArray4(int[] nums) {
int max = Integer.MIN_VALUE,sum=0;
for (int i = 0; i < nums.length; i++) {
if (sum<0)
sum=nums[i];
else
sum+=nums[i];
if (sum>max)
max=sum;
}
return max;
}