求数组中最大和子串类问题

来源:互联网 发布:glide源码 编辑:程序博客网 时间:2024/06/06 11:04
public class maxsub {/* * 基于的性质:1.对于全负的元素,找到最大值即可 * 2.对于最大子串和大于0的,可证明最大子串中任意前缀串大于0 *  * 算法:依次计算累加和,当累加和大于原累加和时记录最大值相关信息,当累加和小于零时,由下一元素重新累加 */static int getmaxsub(int[] a) throws Exception{if(null==a||a.length<=0)throw new Exception();int maxhead=0,maxend=0,max=Integer.MIN_VALUE;int head=0,sum=0;for(int i=0;i<a.length;i++){sum+=a[i];if(sum>max){max=sum;maxhead=head;maxend=i;}if(sum<0){head=i+1;sum=0;}}System.out.printf("\nmaxsub is %d to %d sum=%d\n",maxhead,maxend,max);return max;}static int getMaxsub(int[] a) throws Exception{if(null==a||a.length<=0)throw new Exception();int sum=0,max=Integer.MIN_VALUE;for(int i=0;i<a.length;i++){sum+=a[i];if(sum>max)max=sum;if(sum<0)sum=0;}return max;}static int[] getMaxsub(int[] a,int start,int end) throws Exception{if(null==a||start>=end)throw new Exception();int maxhead=0,maxend=0,max=Integer.MIN_VALUE;int head=0,sum=0;for(int i=start;i<end;i++){sum+=a[i];if(sum>max){max=sum;maxhead=head;maxend=i;}if(sum<0){head=i+1;sum=0;}}return new int[] {max,maxhead,maxend};}public static void main(String[] argvs) throws Exception{int[] a={-2, 1, -3, 4, -1, 2, 1, -5, 4};getmaxsub(a);System.out.println(getMaxsub(a));int[] b = getMaxsub(a,0,a.length);System.out.println(Math.max(getMaxsub(a, 0, b[1])[0],getMaxsub(a,b[2],a.length)[0]));}}

0 0