题意:
如题目所示,就是求一个数组中最大连续子序列之和并且记录开始和结束下标。
这是经典的一个动态规划问题,时间复杂度为O(N)
public class TestMaxQueue { public static void main(String[] args) { // TODO Auto-generated method stub int[] num=new int[]{-2,11,-4,13,-5,-2}; int[] num2=new int[]{-10 ,1 ,2 ,3 ,4 ,-5 ,-23 ,3 ,7, -21}; int[] nums=new int[]{5 ,-8 ,3 ,2 ,5 ,0}; int[] num4=new int[]{-2, 11, -4, 13, -5, 2, -5, -3, 12, -9}; getmax(num4); } public static void getmax(int[] num){ int s=0; int e=0; int max=0; int temp=0; int ts=0; for(int i=0;i<num.length;i++){ temp=temp+num[i]; if(temp<0){ ts=i+1; e=i+1; temp=0; }else{ if(temp>max){ s=ts; e=i; max=temp; } } } System.out.println("maxsum="+max+",start:"+s+",end="+e); } }特别注意:当总和小于0的时候,应该是记录一个重新开始的坐标,到总和大于原来的max的时候才能记录新的起点坐标。