题目描述:给定一个整数数组 nums
,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
题目地址:https://leetcode-cn.com/problems/maximum-subarray/
思路:
1、最大+连续,想到贪心算法的思想,这里设置max初始值为第一个值(可能数组的长度为1或者最大连续子序列的长度为1),依次遍历数组的每一个元素,即用sum加上当前元素,如果sum比max大就更新max,当sum小于0时,表明当前子序列和为负数,则不需要继续加,直接归为0即可。
2、这是第一种思路的简洁版,其中pre保存一种中间状态,看子序列是否加上前一个子序列,若更大则加上,再用当前子序列和与max比较取最大。
代码展示:
1、
/**
* @ClassName Solution
* @Description
* @Author Administrator
* @Date 2020/6/2 8:50
* @Version 1.0
**/
public class Solution {
public int maxSubArray(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int max = nums[0];
int sum = 0;
for (int i = 0; i < nums.length; i++){
sum += nums[i];
if(sum > max){
max = sum;
}
if(sum < 0)
sum = 0;
}
return max;
}
}
2、
/**
* @ClassName Solution1
* @Description
* @Author Administrator
* @Date 2020/6/2 9:10
* @Version 1.0
**/
public class Solution{
public int maxSubArray(int[] nums) {
int pre = 0, max = nums[0];
for(int i = 0; i < nums.length; i++){
pre = Integer.max(pre + nums[i], nums[i]);
max = Integer.max(pre, max);
}
return max;
}
}