package bao; public class Solution { public static void main(String[] args) throws InterruptedException { int[] array = {1,-2,3,10,-4,7,2,-5}; Long begintime = System.nanoTime(); int result = FindGreatestSumOfSubArray(array); Long endtime = System.nanoTime(); System.out.println("连续子数组的最大和为:"+result+",运行时间:"+(endtime - begintime) + "ns"); Thread.sleep(1000); } public static int FindGreatestSumOfSubArray(int[] array) throws InterruptedException { int len = array.length; if (len == 0){ return 0; } int[] currentsum = new int[len]; currentsum[0] = array[0]; int greatsetsum = array[0]; System.out.println("第1步:累加子数组和:"+currentsum[0]+",最大子数组和:"+greatsetsum); Thread.sleep(1000); for(int i=1;i<array.length;i++){ if(currentsum[i-1]>0){ currentsum[i] = currentsum[i-1] + array[i]; }else{ currentsum[i] = array[i]; } if(currentsum[i] > greatsetsum){ greatsetsum = currentsum[i]; } System.out.println("第"+(i+1)+"步:累加子数组和:"+currentsum[i]+",最大子数组和:"+greatsetsum); Thread.sleep(1000); } return greatsetsum; }
运行截图:
学习于网络。