Maximum_Subarray

来源:互联网 发布:js定时器重复执行 编辑:程序博客网 时间:2024/06/06 01:25
packagecom.ytx.dp;
/** 题目描述:给定一个整数数组,如{-1,3,6,0,-9,2,-5,-1,9,3,-3},求该数组中的和最大的连续子序列
 *
 *@authoryuantian xin
 *     
 *     以下是根据之前dp算法的进一步优化,优化空间,并不需要一个数组来打表,可以用两个变量即可。
 */
publicclassMaximum_Subarray {
       
       
       publicintmaxSubArray(int[]A) {
             
             intlen = A.length;
             intmax = Integer.MIN_VALUE;
             inttemp = Integer.MIN_VALUE;
             
             for(inti=0;i<len; ++i){
                if(temp< 0)
                    temp = A[i];
                else{
                    temp += A[i];
                 }
                if(temp> max){
                    max = temp;
                 }
             }
             
             returnmax;
       }
       publicstaticvoidmain(String[] args) {
             
             int[]data = {1,-2,0,0,3,10,-4,7,2,-5,3};
             intmax = new  Maximum_Subarray().maxSubArray(data);
             System.out.println(max);
       }
}