题目:
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
代码:
- 解法一
class Solution {
public int maxSubArray(int[] nums) {
//如果数组长度为1
if(nums.length==1){
return nums[0];
}
int frist,second,max;
max=frist=nums[0];
//遍历数组 寻找出最大值
for(int i=1;i<nums.length;i++){
second=(nums[i]+frist>nums[i]?nums[i]+frist:nums[i]); //前几个元素相加是否大于当前元素的值?大于时最大子串再将当前元素加上:小于时最大子串从当前元素开始
max=Math.max(max,second); //判断当前子串的和与最大值作比较
frist=second; //重置下一次循环应该是接着最长子串 还是重新开启子串(让当前元素做下次循环的字符串的第一个元素)
}
return max; //返回最大值
}
}
- 解法二
class Solution {
public int maxSubArray(int[] nums) {
int min = 0;
int len = nums.length;
//先给countMax赋值
int countMax = nums[0];
//产生全部子串
for (int i = len; i > 0; i--) {
for (int start = 0, end = i - 1; end < len; start++, end++) {
int[] tempNums = Arrays.copyOfRange(nums, start, end + 1);
if (countMax < sum(tempNums)) { //判断子串的求和与countMax的大小
countMax = sum(tempNums);
}
}
}
return countMax;
}
//求子串各元素的和
public int sum(int[] tempNums) {
int tempCount = 0;
for (int i = 0; i < tempNums.length; i++) {
tempCount += tempNums[i];
}
return tempCount;
}
}
- 别人的代码
class Solution {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int curSum = 0;
for (int n: nums) {
curSum += n;
if (curSum > maxSum) { maxSum = curSum; }
if (curSum < 0) { curSum = 0; }
}
return maxSum;
}
}