题目描述:
第一种解法(时间复杂度为O(n^2)):
package com.DJL.ArraysMatrix;
/**
* @author DJL
* @create 2021-08-03 14:43
*/
public class Practice_求和最大连续子数组 {
//暴力破解法,时间复杂度为:O(n)
static void sovel_1(int[] arr) {
int maxSum = arr[0];
for (int i = 0; i < arr.length; i++) {
int sum = arr[i];
int maxOfJ = sum;
for (int j = i + 1; j < arr.length; j++) {
sum += arr[j];
if (sum > maxOfJ) {
maxOfJ = sum;
}
}
if (maxOfJ > maxSum) {
maxSum = maxOfJ;
}
}
System.out.println(maxSum);
}
public static void main(String[] args) {
int[] arr = {1, -2, 3, 5, -2, 6, -1};
sovel_1(arr);
}
}
运行结果:12
第二种解法(时间复杂度为O(n)):
package com.DJL.ArraysMatrix;
public class Practice_求和最大连续子数组 {
//递推法,时间复杂度为O(n)
static void solve_2(int[] arr) {
int sumJ = arr[0];
int max = sumJ;
int left = 0;
int right = 0;
for (int j = 1; j < arr.length; j++) {
if (sumJ >= 0) {
sumJ += arr[j];
} else {
sumJ = arr[j];
left = j;
}
if (sumJ > max) {
max = sumJ;
right = j;
}
}
System.out.println(max + " " + left + "->" + right);
}
public static void main(String[] args) {
int[] arr = {1, -2, 3, 5, -2, 6, -1};
solve_2(arr);
}
}
运行结果:12