贴图贴代码
package LeetCode;
import java.util.Scanner;
/**
* @author LzStart
* @create 2022-03-24-13:05
*/
public class Max_SubArray {
public static int max_Sum = 0; //存储最大子序列和
public static int left; //左指针,指向最大子序列的起点
public static int right; //右指针,指向最大子序列的终点
public static void process(int[] arr, int low, int high) {
if (arr == null || arr.length < 2) {
return;
}
int mid = low + ((high - low) >> 1);
if ((high - low) >> 1 >= 1) {
process(arr, low, mid);
process(arr, mid + 1, high);
if (max_SubArray(arr, low, high) > max_Sum) {
max_Sum = max_SubArray(arr, low, high);
}
}
}
public static int max_SubArray(int[] arr, int low, int high) {
int max_Sum_1 = 0;
int max_Sum_2 = 0;
int mid = low + ((high - low) >> 1);
//从 mid 出发往两边走,分别得到往左走的最大值和往右走的最大值,将两者相加
int sum = 0;
for (int i = mid; i >= low; i--) {
sum = sum + arr[i];
if (sum > max_Sum_1) {
max_Sum_1 = sum;
left = i;
}
}
sum = 0;
for (int j = mid; j <= high; j++) {
sum = sum + arr[j];
if (sum > max_Sum_2) {
max_Sum_2 = sum;
right = j;
}
}
return max_Sum_1 + max_Sum_2 - arr[mid];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("输入数组长度:");
int n = scanner.nextInt();
System.out.print("输入数组:");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
int num = scanner.nextInt();
arr[i] = num;
}
process(arr, 0, arr.length - 1);
System.out.println("该数组最大子序列和为:" + max_Sum);
System.out.print("该数组最大子序列为: ");
for (int i = left; i <= right; i++) {
System.out.print(arr[i] + " ");
}
}
}