zoukankan      html  css  js  c++  java
  • 首尾相连一维数组的最大子数组和

    一、设计思路:与求数组的最大子数组相同,先遍历所有子数组,然后判断最后一个子数组是否大于0。若大于0,则重头开始遍历,直到子数组的和小于0或者到最后一个子数组的前一个数为止,在此过程中保存子数组的最大值以及位置。

    二、代码:

    import java.util.Scanner;
    
    public class main {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int i;
            int s=0,sum=0,head=0,end=0,h=0,e=0;
            Scanner sc=new Scanner(System.in);
            System.out.print("请输入数组长度:");
            int x=sc.nextInt();
            int a[]=new int[x];
            System.out.print("请输入数组中的数:");
            for(i=0;i<x;i++)
            {
                a[i]=sc.nextInt();
            }
            
            
            for(i=0;i<x;i++)
            {
                s+=a[i];
                if(s>0)
                {
                    e++;
                }
                else
                {
                    s=0;
                    h=i+1;
                    e++;
                }
                if(s>sum)
                {
                    sum=s;
                    head=h;
                    end=e;
                }
            }
            if(s>0)
            {
                head=h;
                i=0;
                e=e-x;
                while(s>0&&e!=h-1)
                {
                    s+=a[i];
                    i++;
                    e++;
                    if(s>sum)
                    {
                        sum=s;
                        end=e;
                    }
                }
            }
            System.out.print("最大子数组的和为:");
            System.out.println(sum);
            System.out.print("最大子数组为:");
            if(end>head)
            {
                for(i=head;i<end;i++)
                {
                    System.out.print(a[i]);
                    System.out.print(" ");
                }
            }
            else
            {
                for(i=head;i<x;i++)
                {
                    System.out.print(a[i]);
                    System.out.print(" ");
                }
                for(i=0;i<end;i++)
                {
                    System.out.print(a[i]);
                    System.out.print(" ");
                }
            }
            
        }
    
    }
    

    三、结果截图:

    四、总结:在这个任务当中我负责测试方面。通过与郭昊同学一起讨论程序如何编写这个程序提升了我在整体思考方面的意识,对我以后在编程方面有更加完善的思考有很大帮助。其次,我与郭昊同学都勇于指出对方的不足以及让我们在团队合作方面统一了字符缩进等编程习惯。这有助于我们以后编程之路的发展,

    五、结组成员:杜永超(负责测试)、郭昊(负责编程)

  • 相关阅读:
    windows nginx
    stdClass 标准
    array_merge
    array_pop
    array_push
    array_unique
    GMT与UTC简介(转)
    curl-手册
    13.5. zipfile — Work with ZIP archives
    7. Input and Output
  • 原文地址:https://www.cnblogs.com/dyc940210/p/4430138.html
Copyright © 2011-2022 走看看