zoukankan      html  css  js  c++  java
  • 求数组的子数组之和的最大值

    题目:

      输入一个整形数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。 求所有子数组的和的最大值。要求时间复杂度为O(n)。

    思路:

      首先肯定是建立数组,考虑数组元素来源,可随机生成,亦可自己输入。

      对于算法,在课上的时候没有想出O(n)的,只想到了O(n^2)的,就是先两次循环求出各个子数组的和,将求解存到新的数组中,最后对储存各个子数组的和的数组进行比较求取最大值。

    源代码:

    package demo;
    
    import java.util.Scanner;
    
    public class shuzu {
        
        public static void main(String[] args) {
            @SuppressWarnings("resource")
            Scanner cin = new Scanner(System.in);
            int [] mylist = new int[1000];                 //建立一个长度为1000的整型数组,用来储存输入的数组
            int [] jieguo = new int[1000];
            int n ;
            int max = 0;
            int mlist,slist=0;                            //slist为子数组和
            System.out.println("输入整数数组的长度:");
            n = cin.nextInt();
            for(int i = 0;i < n ;i++)                    //进行数组输入
                mylist[i]=cin.nextInt();
            for(int i=0;i<n;i++)                        //O(n^2)求子数组之和
            {
                mlist = 0;
                for(int j=i;j<n;j++)
                {
                    mlist +=mylist[j];
                    jieguo[slist++] = mlist;            //将子数组之和存在数组jieguo[]内
                    System.out.println("第"+ slist +"个子数组的和为:" + mlist);
                }
            }
            max = jieguo[0];                            //将子数组和数组第一个值给max,然后循环进行比较,求出最大值
            for(int i = 0;i<slist;i++)
            {
                if(max < jieguo[i])
                    max = jieguo[i];
            }
            System.out.println("最大子数组和为:" + max);
        }
    
    }
  • 相关阅读:
    Entity SQL 初入
    ObjectQuery查询及方法
    Entity Framework 的事务 DbTransaction
    Construct Binary Tree from Preorder and Inorder Traversal
    Reverse Linked List
    Best Time to Buy and Sell Stock
    Remove Duplicates from Sorted Array II
    Reverse Integer
    Implement Stack using Queues
    C++中const限定符的应用
  • 原文地址:https://www.cnblogs.com/flw0322/p/10506937.html
Copyright © 2011-2022 走看看