軟體工程子數組求和2

來源:互聯網
上載者:User

標籤:max   限制   new   can   gen   無法   軟體   return   int   

1.設計思想:首先想到首尾相連和不相連的區別在哪?區別在最後一個數還可以和前面的數組成一個新的數組;然後就是怎樣考慮

用數組儲存首尾相連的數組,是否需要加入其他限制條件等?

 

2.出現的問題:首尾相連數組無法同其他數組一樣儲存到一個數組中。

 

4.原始碼:

package 子數組求和2;

import java.util.Scanner;

public class test {

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=findMaxSum(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(findMaxSum(a,n)>=sum)
{
sum=findMaxSum(a,n);
}
}
int a2=sum;
if(a1>=a2)
{
System.out.println("最大子數組和:" + a1);
}
else
{
System.out.println("最大子數組和:" + a2);
}


}
public static int findMaxSum(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;
}
}

 

軟體工程子數組求和2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.