前言
之前入门算法用代码随想录(代码随想录),将递归,动态规划这些都学了一遍,也自己动手实现过,但之前也是边参考边写出来的,而且隔了有一段时间了,最近二刷一次!!这次挑战尽量自己写出来。
链接
代码
public class _33_53_最大子序和 {
public static void main(String[] args) {
System.out.println(maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
}
/**
* 给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
*
* 子数组 是数组中的一个连续部分。
*/
public static int maxSubArray(int[] nums) {
int count = 0;
int max = Integer.MIN_VALUE;
for(int i = 0; i < nums.length; i++){
count += nums[i];
max = Math.max(max,count);
if(count < 0){
count = 0;
}
}
return max;
}
}