通过一个动态规划的例子来体会时间复杂度的不同

public class Main {
    public static void main(String[] args) {
    // write your code here
        int N = 10000;
        int[] A = new int[N];
        for(int i = 0; i < N; i++){
            A[i] = (int)(Math.random() * N + 1);
        }
        long startTime=System.nanoTime();
        int res = MaxSubsequenceSum_4(A, N);
        long endTime=System.nanoTime();
        System.out.println(res);
        System.out.println("程序运行时间: "+(endTime - startTime)+"ns");

    }

    //Algorithm 1      O(N^3)
    public static int MaxSubsequenceSum_1(final int A[], int N){
        int ThisSum, MaxSum = 0;
        for(int i = 0; i < N; i++){
            for(int j = i; j < N; j++){
                ThisSum = 0;
                for(int k = i; k <= j; k++){
                    ThisSum += A[k];
                }
                if(ThisSum > MaxSum){
                    MaxSum = ThisSum;
                }
            }
        }
        return MaxSum;
    }
//    Algorithm2       O(N^2)
    public static int MaxSubsequenceSum_2(final int A[], int N){
        int ThisSum, MaxSum = 0;
        for(int i = 0; i < N; i++){
            for(int j = i; j < N; j++){
                ThisSum = A[j];
                if(ThisSum > MaxSum){
                    MaxSum = ThisSum;
                }
            }
        }
        return MaxSum;
    }
//Algorithm4            O(N)
    public static int MaxSubsequenceSum_4(final int A[], int N){
        int ThisSum = 0, MaxSum = 0;
        for(int j = 0; j < N; j++){
            ThisSum += A[j];
            if(ThisSum > MaxSum){
                MaxSum = ThisSum;
            }
            else if(ThisSum < 0){
                ThisSum = 0;
            }
        }
        return MaxSum;
    }
}

 

转载于:https://www.cnblogs.com/zhaijiayu/p/11563281.html

你可能感兴趣的:(通过一个动态规划的例子来体会时间复杂度的不同)