C編程筆試 --“最大子數(shù)組的和” 的動態(tài)規(guī)劃的解法
?1.最大子數(shù)組之和
例1:數(shù)組int a1[5] = { -1, 5, 6, -7, 3 };其最大子數(shù)組之和為:5+6=11
例2:數(shù)組int a2[5] = { -5, -4, -8, -1, -10 };其最大子數(shù)組之和為:-1
例3:數(shù)組 int a3[5] = { -1, 5, 6, -7, 10 };其最大子數(shù)組之和為:5+6-7+10=14
??功能實現(xiàn):
# include
# include
int MaxSum(int* arr, int size)
{
int current = arr[0]; //當前數(shù)組最大和
int max = current;
for (int i = 0; i < size; i++)
{
if (current < 0)
current = 0;
current += arr[i];
if (current > max)
max = current;
}
return max;
}
int main(void)
{
char x[40], y[40];
int a1[5] = { -1, 5, 6, -7, 3 };
int a2[5] = { -5, -4, -8, -1, -10 };
int a3[5] = { -1, 5, 6, -7, 10 };
int max1, max2, max3;
max1 = MaxSum(a1, 5);
max2 = MaxSum(a2, 5); //這個應(yīng)該返回 -1,
max3 = MaxSum(a3, 5);
printf("max1=%d,max2=%d,max3=%d\n",max1,max2,max3);
}
?2.獲取最大子數(shù)組的開始和結(jié)束的下標
??如果我需要返回值返回這個最大子數(shù)組的開始和結(jié)束的下標,你要怎么修改這個程序?
例1:數(shù)組int a1[5] = { -1, 5, 6, -7, 3 };其最大子數(shù)組之和為:5+6=11;最大子數(shù)組開始和結(jié)束下標為:1 2。
例2:數(shù)組int a2[5] = { -5, -4, -8, -1, -10 };其最大子數(shù)組之和為:-1;最大子數(shù)組開始和結(jié)束下標為:3 3。
例3:數(shù)組 int a3[5] = { -1, 5, 6, -7, 10 };其最大子數(shù)組之和為:5+6-7+10=14 ; 最大子數(shù)組開始和結(jié)束下標為:1 4。
例4:數(shù)組 int a3[] = {-2, -1, -3, 4, -1, 2, 1, -5, 4};其最大子數(shù)組之和為:4+(-1)+2+1=6 ; 最大子數(shù)組開始和結(jié)束下標為:3 6。
??功能實現(xiàn):
#include
#include
void solution(int m, int *arr){
int current=arr[0];
int max=current;
int start=0,end=0;
int i=0;
/*計算最大子數(shù)組之和*/
for(i=1;imax)
{
max = current;
end=i;//最大子數(shù)組結(jié)束下標
}
}
int temp=max;
/*計算最大子數(shù)組結(jié)束下標*/
for(i=end;i>=0;i--)
{
temp-=arr[i];
if(temp<=0 || temp>max)break;
}
if(i<0)i=0;
start=i;
printf("%d,%d %d\n",max,start,end);
}
int main() {
int n;
printf("輸入個數(shù):");
scanf("%d", &n);
int *arr;
arr = (int*)malloc(n * sizeof(int));
printf("輸入%d個整數(shù):",n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
solution(n, arr);
return 0;
}
;i++)>
??運行結(jié)果:
![pYYBAGMBfYaAP_I9AAMUkvwWkUo576.png#pic_center](https://file.elecfans.com//web2/M00/63/E2/pYYBAGMBfYaAP_I9AAMUkvwWkUo576.png#pic_center)
-
C語言
+關(guān)注
關(guān)注
180文章
7614瀏覽量
137827 -
數(shù)組
+關(guān)注
關(guān)注
1文章
417瀏覽量
26034
發(fā)布評論請先 登錄
相關(guān)推薦
數(shù)組的下標為什么可以是負數(shù)
數(shù)組名之間可以直接賦值嗎
指針數(shù)組和二維數(shù)組有沒有區(qū)別
C語言數(shù)組應(yīng)用計算機導(dǎo)論A第6講:數(shù)組
C語言中的socket編程基礎(chǔ)
labview字符串數(shù)組轉(zhuǎn)化為數(shù)值數(shù)組
PLC編程語言和C語言的區(qū)別
嵌入式中零長度數(shù)組基本操作方法
![嵌入式中零長度<b class='flag-5'>數(shù)組</b>基本操作方法](https://file1.elecfans.com//web2/M00/E5/26/wKgaomY_FmCASuqKAACr-GPuQ2c182.png)
深入探索KUKA KRL中的數(shù)組應(yīng)用
![深入探索KUKA KRL中的<b class='flag-5'>數(shù)組</b>應(yīng)用](https://file1.elecfans.com/web2/M00/CC/61/wKgZomYgh_6AQodBAAAc_c8kLRY926.png)
嵌入式系統(tǒng)中C語言結(jié)構(gòu)體的基礎(chǔ)實現(xiàn)與應(yīng)用
![嵌入式系統(tǒng)中<b class='flag-5'>C</b>語言結(jié)構(gòu)體的基礎(chǔ)實現(xiàn)與應(yīng)用](https://file1.elecfans.com/web2/M00/C4/E6/wKgaomXv9r6Aaj6DAAAYJ3PfWAU110.jpg)
評論