最大子序列和最大递增子序列

给定K个整数的序列{ N1, N2, ..., NK },其任意连续子序列可表示为{ Ni, Ni+1, ..., 
Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个, 
例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和 
为20。 
在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该 

子序列的第一个和最后一个元素。

关于这个问题,我参考了三篇博客, http://blog.csdn.net/superchanon/article/details/8228212

http://blog.csdn.net/qq_16542775/article/details/44783077

http://blog.csdn.net/ssuchange/article/details/17341693 输出子序列

package PaixuExercise;
import java.util.*;

public class MaxSunSequence {
	public static void main(String[] args){
//		Scanner scan = new Scanner(System.in);
//		while(scan.hasNext()){
//			int number = scan.nextInt();
//			int[] arr = new int[number]; 
//			for(int i=0;i maxSum){
					maxSum = sum;
				}
			}
		}
		return maxSum;
	}
	//http://blog.csdn.net/qq_16542775/article/details/44783077
	public static int subSequence(int[] arr){
		int sum,maxSum,start,end,cnt;
		int temp = 0;
		maxSum = 0;
		sum = start = end = 0;
		cnt = 0;
		for(int i=0;i maxSum){
				maxSum = sum;
				end = i;
				start = temp;
			}else{
				if(sum < 0){
					sum = 0;
					temp = i+1;
					cnt++;
				}
			}
		}
		if(cnt == arr.length){
			System.out.println("全为负数");
		}
		
		return maxSum;
	}
	
	//http://blog.csdn.net/ssuchange/article/details/17341693 输出子序列
	public static void maxSubsequence(int[] array) {

        if (array.length <= 0)

            return;

        int[] sum =new int[array.length];

        int maxSum = array[0];

        for (int i = 0; i < array.length; i++) {

            if (i == 0)

                sum[i] = array[i];

            else {

                //if(sum[i-1]>=0 && arr[i-1] < arr[i])   最大递增自序列
            	if (sum[i - 1] >= 0)

                    sum[i] = sum[i - 1] +array[i];

                else

                    sum[i] = array[i];

            }

            if (maxSum < sum[i])

                maxSum = sum[i];

        }

        System.out.println("MaxSum:\t" + maxSum);

        System.out.println("--------------------");

        for (int i = 0; i < sum.length; i++) {

            if (sum[i] == maxSum) {

                int j = i;

                while (j >= 0 && sum[j] >= 0){

                    j--;
                }
                System.out.print("MaxSubsequence:\t");

                for (j++; j <= i; j++)
                {
                    System.out.print(array[j] +" ");
                }
                System.out.println();

                System.out.println("--------------------");

            }

        }

        System.out.println("******************");

    }

 

    public static void testmaxSubsequence() {

        int[] array;

        array = new int[] { 5, -3, 4, 2 };

        maxSubsequence(array);

        array = new int[] { 5, -6, 4, 2 };

        maxSubsequence(array);

        array = new int[] { 5, -6, 4, 2, -10, 5, -6, 4, 2 };

        maxSubsequence(array);

    }
}


你可能感兴趣的:(动态规划)