java (數組)

來源:互聯網
上載者:User

標籤:turn   com   scan   多選   port   ring   tin   UI   多個   

一、題目要求:

輸入一個一維整形數組,數組裡有正數也有負數。

一維數組首尾相接,像個一條首尾相接帶子一樣。

數組中連續的一個或多個整數組成一個子數組,每個子數組都有一個和。求所有子數組的和的最大值。

發表一篇部落格文章講述設計思想,出現的問題,可能的解決方案(多選)、原始碼、結果、總結。

二丶設計思想:

遍曆數組裡面的每一個數將第一個數變為最後一個數,具體演算法 a[i-1]=a[i],這樣又變成了一個新的一維數組,輸出每個數組的最大子數組和,然後比較每個輸出的和,找出最大的數

三丶代碼

import java.util.Scanner; public class shuzu {     public static void main(String[] args) {        // TODO Auto-generated method stub        Scanner scan=new Scanner(System.in);        System.out.print("請輸入數組中數位個數:");        int n=scan.nextInt();        int[] a=new int [n];        System.out.print("請輸入數組:");        for(int i=0;i<n;i++)        {           a[i]=scan.nextInt();        }        int a1=zuida(a,n);        int b,temp,i,sum=0;        for(b=1;b<n;b++)        {            temp=a[0];            for(i=1;i<=n-1;i++)            {               a[i-1]=a[i];                    }            a[n-1]=temp;            if(zuida(a,n)>=sum)            {             sum=zuida(a,n);            }        }        int a2=sum;        if(a1>=a2)        {            System.out.println("最大子數組和:" + a1);        }        else        {            System.out.println("最大子數組和:" + a2);        }                  }     public static int zuida(int a[],int n)     {         int sum=0;                      int b=0;                           for(int i=0; i<n; i++)            {                if(b<0)                            b=a[i];                else                    b+=a[i];                if(sum<b)                    sum=b;            }            return sum;     }}

四丶運行

 

java (數組)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.