package project; import java.util.ArrayList; import java.util.Scanner; public class read1 { class KadaneResult { int maxSum; int start; int end; public KadaneResult(int maxSum, int start, int end) { this.maxSum = maxSum; this.start = start; this.end = end; } } public ArrayList<String> kadane(int arr[]) { ArrayList<String> process = new ArrayList<>(); int max = 0; int maxStart = -1; int maxEnd = -1; int currentStart = 0; int maxSoFar = 0; for (int i = 0; i < arr.length; i++) { maxSoFar += arr[i]; if (maxSoFar < 0) { maxSoFar = 0; currentStart = i + 1; } if (max < maxSoFar) { maxStart = currentStart; maxEnd = i; max = maxSoFar; } process.add(i + ":" + printOut(arr, maxStart, maxEnd, maxSoFar)); } return process; } private String printOut(int arr[], int maxStart, int maxEnd, int maxSoFar) { String aString = new String(); for (int i = 0; i < arr.length; i++) { if (i == maxStart || i == maxEnd) { aString += ("[" + arr[i] + "]"); } else { aString += (arr[i]); } if (i < arr.length - 1) { aString += (" "); } else { aString += (" 当前最大子数组和为{" + maxSoFar + "}"); } } return aString; } public static void main(String[] args) { read1 arrayList = new read1(); int[] a = { 1, 3, -9, 6, 2, 4, 1, 5, 8 }; ArrayList<String> arrayList2 = arrayList.kadane(a); Scanner inScanner = new Scanner(System.in); int i = -1; boolean flag = true; while (flag) { System.out.println("1.下一步 2.上一步 3.回滚到第几步"); switch (inScanner.nextInt()) { case -1: System.out.println("已经到顶"); case 1: if (i + 1 >= arrayList2.size()) { System.out.println("已经到底"); break; } System.out.println(arrayList2.get(++i)); break; case 2: System.out.println(arrayList2.get(--i)); break; case 3: System.out.println("回滚到第..步"); i = inScanner.nextInt(); System.out.println(arrayList2.get(i)); break; default: flag = false; break; } } } }