• 求最大子数组和


    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Scanner;
    
    
    public class MaxSubArray {
    
        /**
         * @param args
         * @throws IOException 
         */
        public static void main(String[] args) throws IOException {
            // TODO Auto-generated method stub
    
            Scanner in=new Scanner(System.in);
            int n;
            System.out.println("输入数组元素个数");
            n=in.nextInt();
            int []array=new int[n];
            System.out.println("输入数组元素");
            for(int i=0;i<n;i++)
            {
                array[i]=in.nextInt();
            }
            int []doubleArray=new int[2*n];
            for(int i=0;i<n;i++)
            {
                doubleArray[i]=array[i];
            }
            for(int j=0;j<n;j++)
            {
                doubleArray[j+n]=array[j];
            }
            //验证doubleArray在排列上是否为array数组*2
            /*for(int m=0;m<2*n;m++)
            {
                System.out.print(doubleArray[m]);
            }*/
            
            //列举所有子数组和
            System.out.println("子数组的和为:");
            File file=new File("max.txt");
            FileWriter fw=new FileWriter(file);
            int max=0;
            for(int i=0;i<n;i++)
            {
                int flag=0;
                for(int j=i;j<2*n;j++)
                {
                    
                    max=max+doubleArray[j];
                    flag++;
                    System.out.print(max+" ");
                    fw.write(max+"
    ");//所有子数组的和写入max文件
                    if(flag==n)//达到数组最大长度跳出循环
                        break;
                }
                max=0;//归零
                System.out.println();
            }
            fw.close();
            System.out.println();
            //读取max文件子数组和并获取最大值
            FileReader fr=new FileReader("max.txt");
            BufferedReader br=new BufferedReader(fr);
            int[]GetMax=new int[n*n];
            String line;
            int j = 0;
            while((line=br.readLine())!=null)
            {
                GetMax[j++]=Integer.parseInt(line);    
            }
            br.close();
            int SubMax=GetMax[0];
            for(int i=0;i<n*n;i++)
            {
                if(GetMax[i]>SubMax)
                    SubMax=GetMax[i];
            }
            System.out.println("子数组和最大值为"+SubMax);
        }
    
    }

    输入一个一维整形数组,里面有整数也有负数

    一位数组首尾相接,像一条首尾相接的带子

    数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和

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

    运行结果截图

    将数组中的元素安春旭一次向后累加,同事如果遇到负数那么一定会变小,将其写入保存,读出其中和的最大值

  • 相关阅读:
    最小路径
    零钱兑换
    硬币
    三步问题
    区域和检索
    除数博弈
    URI和URL的辨别
    交叉编译OpenMP
    牛客挑战赛44D-数列的和
    CF1408H. Rainbow Triples
  • 原文地址:https://www.cnblogs.com/xhxdeblog/p/6652885.html
Copyright © 2020-2023  润新知