C編程筆試 --“最大子數(shù)組的和” 的動(dòng)態(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
??功能實(shí)現(xiàn):
# include
# include
int MaxSum(int* arr, int size)
{
int current = arr[0]; //當(dāng)前數(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); //這個(gè)應(yīng)該返回 -1,
max3 = MaxSum(a3, 5);
printf("max1=%d,max2=%d,max3=%d\n",max1,max2,max3);
}
?2.獲取最大子數(shù)組的開(kāi)始和結(jié)束的下標(biāo)
??如果我需要返回值返回這個(gè)最大子數(shù)組的開(kāi)始和結(jié)束的下標(biāo),你要怎么修改這個(gè)程序?
例1:數(shù)組int a1[5] = { -1, 5, 6, -7, 3 };其最大子數(shù)組之和為:5+6=11;最大子數(shù)組開(kāi)始和結(jié)束下標(biāo)為:1 2。
例2:數(shù)組int a2[5] = { -5, -4, -8, -1, -10 };其最大子數(shù)組之和為:-1;最大子數(shù)組開(kāi)始和結(jié)束下標(biāo)為:3 3。
例3:數(shù)組 int a3[5] = { -1, 5, 6, -7, 10 };其最大子數(shù)組之和為:5+6-7+10=14 ; 最大子數(shù)組開(kāi)始和結(jié)束下標(biāo)為:1 4。
例4:數(shù)組 int a3[] = {-2, -1, -3, 4, -1, 2, 1, -5, 4};其最大子數(shù)組之和為:4+(-1)+2+1=6 ; 最大子數(shù)組開(kāi)始和結(jié)束下標(biāo)為:3 6。
??功能實(shí)現(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;
/*計(jì)算最大子數(shù)組之和*/
for(i=1;imax)
{
max = current;
end=i;//最大子數(shù)組結(jié)束下標(biāo)
}
}
int temp=max;
/*計(jì)算最大子數(shù)組結(jié)束下標(biāo)*/
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("輸入個(gè)數(shù):");
scanf("%d", &n);
int *arr;
arr = (int*)malloc(n * sizeof(int));
printf("輸入%d個(gè)整數(shù):",n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
solution(n, arr);
return 0;
}
;i++)>
??運(yùn)行結(jié)果:

-
C語(yǔ)言
+關(guān)注
關(guān)注
180文章
7628瀏覽量
139697 -
數(shù)組
+關(guān)注
關(guān)注
1文章
419瀏覽量
26294
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
C++學(xué)到什么程度可以找工作?
數(shù)組的下標(biāo)為什么可以是負(fù)數(shù)
數(shù)組名之間可以直接賦值嗎
指針數(shù)組和二維數(shù)組有沒(méi)有區(qū)別
C語(yǔ)言數(shù)組應(yīng)用計(jì)算機(jī)導(dǎo)論A第6講:數(shù)組
解讀版|Air780E軟件中C語(yǔ)言內(nèi)存數(shù)組的神秘面紗!

C語(yǔ)言中的socket編程基礎(chǔ)
多臺(tái)倉(cāng)儲(chǔ)AGV協(xié)作全局路徑規(guī)劃算法的研究

放大電路動(dòng)態(tài)分析的基本方法
動(dòng)態(tài)可編程增益放大器

labview字符串數(shù)組轉(zhuǎn)化為數(shù)值數(shù)組
為什么有些TINA-TI仿真可以實(shí)現(xiàn)穩(wěn)態(tài)求解法分析,而有些不行?
PLC編程語(yǔ)言和C語(yǔ)言的區(qū)別
嵌入式中零長(zhǎng)度數(shù)組基本操作方法

評(píng)論