求所有子数组的和的最大值

package shuzu;

public class shuzu {
    public static void main(String[] args) {
        //时间复杂度没有实现,只是实现了输出最大值
        int nshu;//循环的次数
        int shu[] = {-1,3,-6,-5,-2}; 
        int max = shu[0];//存储最大的和
        for(nshu=0;nshu<5;nshu++) {
            int n1 = 0;
            int n2 = 0;
            for(int nnshu=nshu;nnshu<5;nnshu++) {
                n1 = n1 + shu[nnshu];
                if(nnshu<4) {
                    nnshu = nnshu + 1;
                    n2 = n1 + shu[nnshu];
                    max = maxxx(n1,n2,max);
                    nnshu = nnshu - 1;
                }else {
                    max = maxx(n1,max);
                }
            }
        }
        System.out.println("最大值" + max);
    }
    
    static int maxxx(int a,int b,int ab) {
        int max;
        if(a<b) {
            max = b;
            if (max<ab) {
                max = ab;
            }
        }else {
            max = a;
            if(max<ab) {
                max = ab;
            }
        }
        return max;
    }
    
    static int maxx(int a , int b){
        int max;
        if(a<b) {
            max = b;
        }else {
            max = a;
        }
        return max;
    }
    
    
}
 

就是进行两次的循环比较,如果是两次的循环就无法将时间复杂度控制在O(n),至于解决方案只能是利用方法的嵌套。

这次的实验让我切实的认识了时间复杂度的一些相关东西,总的来说通过方法的改变来使空间复杂度和时间复杂度进行变化应该是我接下来应该学习的东西之一。

猜你喜欢

转载自www.cnblogs.com/hwh000/p/10524649.html