描述
给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。
样例
样例1:
输入:[−2,2,−3,4,−1,2,1,−5,3]
输出:6
解释:符合要求的子数组为[4,−1,2,1],其最大和为 6。
样例2:
输入:[1,2,3,4]
输出:10
解释:符合要求的子数组为[1,2,3,4],其最大和为 10
我的代码:
public int maxSubArray(int[] arr) {
// write your code here
Integer max_sum = Integer.MIN_VALUE;
int sum = 0;
for (int i = 0; i < arr.length; i++) {
if(sum < 0) {
sum = 0;
}
sum = sum + arr[i];
if(max_sum < sum) {
max_sum = sum;
}
}
return max_sum;
}
最大连续数组:暴力:三个for 时间复杂度:n的立方
分治:递归的/2 时间复杂度:nlogn
分析法: 时间复杂度:n
来源:CSDN
作者:lmy9213
链接:https://blog.csdn.net/lmy9213/article/details/104397852