最大子序列和

最大子序列和

public class DynamicPlanning { public static int[] dynamic(int[] array) { int length = array.length; int t = array[length - 1]; int max = array[length - 1]; int start = length - 1; int stop = length - 1; for (int i = length - 2; i >= 0; i--) { if (t > 0) { t = array[i] + t; } else { t = array[i]; } if (t >= max) { max = t; start = i; } } int temp_max = max; for (int i = start; i < length - 1; i++) { temp_max -= array[i]; if (temp_max == 0) { stop = i; break; } } start++; stop++; int[] result = { max, start, stop }; return result; } public static void main(String[] args) { int[] array0 = { 6, -1, -5, -4, -7, 34 }; int[] array1 = { 0, 6, -1, 1, -6, 7, -5 }; int[] array2 = { 0, 0, 0, 3, -1, 5 }; ArrayMerge.printIntArray(dynamic(array0)); ArrayMerge.printIntArray(dynamic(array1)); ArrayMerge.printIntArray(dynamic(array2)); } }

你可能感兴趣的:(最大子序列和)