数组中求子数组和最大
要求數組中子數組和的最大值用了兩次循環的辦法,
方案1:塊內先比較大小,一塊一塊的進行,需要嵌套循環
方案2:兩個數的子數組先比較,然后三個數的,四個數的.....再比較,可以不嵌套循環但感覺不夠方便,所以沒用。
方案1,2見圖片分析
源碼:
#include<iostream>
using namespace std;
int max()
{
??? int h=10;
??? int a[10]={9,-3,-4,5,6,-67,-8,-9,0,-12};//定義數組
??? int n=a[0];
??? for(int i=0;i<h;i++)//循環比較
?{
?????? int m=a[i];
?????? for(int j=i+1;j<h;j++)
??? {
????????? m=m+a[j];//數據累加
?????? if(m>=n)
???? n=m;
??? }
?}
??? for(int j=0;j<h;j++)//與每個數組成員比較,看哪個最大
???????? if(a[j]>n)
??? ? ?n=a[j];
??? return n;
}
int main()
{
??? int b=max();
??? cout<<b<<endl;
??? return 0;
}
測試數據:0,-1,-2,-3,-4,-5,-6,-7,-8,-9???????? ?輸出:0;
測試數據:1,2,5,-9,0,-2,-6,-7,-8,-11; 輸出:8;
測試數據:-1,2,5,0,-2,10,-5,-6,-7,5;??? 輸出:15;
?
轉載于:https://www.cnblogs.com/lpjdbk/p/3591746.html
總結
以上是生活随笔為你收集整理的数组中求子数组和最大的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Eclipse 快捷键(转载)
- 下一篇: showModalDialog sesi