定义一个数组返回最大子数组的值(1)
生活随笔
收集整理的這篇文章主要介紹了
定义一个数组返回最大子数组的值(1)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
對于老師上課的題目,要想獲得子函數(shù)最大值,首先進行數(shù)組的遍歷,在遍歷起初,對最大值進行初始化為數(shù)組的第一個元素,每次遍歷,求得該子數(shù)組的和,并將此和與最大值進行比較,若小于
最大值,則進行下一次的遍歷,直到結束。此處用到三個for循環(huán),來進行次數(shù)的控制。第一個?for(i = 0; i <length; i++),用來完成所有數(shù)組的循環(huán),第二個for(j = i; j
<length; j++)用來表示從第幾個元素開始,尋找子數(shù)組,第三個?for( k = i; k <= j; k++) ,用來獲取每個子數(shù)組的和,等到遍歷完全結束,返回最大值輸出。
package bigzishuzu; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub int [] num=new int[30]; int n; int i,j; int cishu; int sum; int max; max=0; cishu=0; System.out.println("請輸入數(shù)組的個數(shù):"); @SuppressWarnings("resource") Scanner scan=new Scanner(System.in); n=scan.nextInt(); int geshu=((1+n)*n)/2; int [] daxiao=new int[300]; for(i=0;i<n;i++) { //完成數(shù)組的的輸入 num[i]=scan.nextInt(); } for(i=0;i<n-0;i++) { sum=0; for(j=i;j<n;j++) { sum=sum+num[j]; System.out.println("第"+cishu+"個子數(shù)組的和為:"+sum); daxiao[cishu]=sum; cishu++; } } max=daxiao[0]; for(int l=0;l<geshu;l++) { if(max<daxiao[l]) { max=daxiao[l]; } } System.out.println("最大子數(shù)組和為:"+max); } }
轉載于:https://www.cnblogs.com/muailiulan/p/11070544.html
總結
以上是生活随笔為你收集整理的定义一个数组返回最大子数组的值(1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 去中心化交易所前路明朗,基于EOS的去中
- 下一篇: 企业级 SpringBoot 教程 (十