MeC*_*ris 0 c arrays numbers sum
我正在学习C,我的老师给了我一个任务,但我被困住了.在数组中有10个正数,我需要找到具有最高总和的3个连续数字.我在网上找到了这个解决方案,但是如何找到3个连续数字并求它们呢?我该怎么做呢?我应该在数组中查找最大数字并从那里开始吗?我发现的代码在我到目前为止做得更好.
该数组具有:{1,2,3,2,0,5,1,6,0,1},那么3个数字的最大总和将是{ 1,2,3,2,0,5,1,6,0,1},因为它给出了12
#define N_ELEMENTS 10
int main(int argc, const char * argv[]) {
int a[N_ELEMENTS] = {1, 2, 3, 2, 0, 5, 1, 6, 0, 1};
int i = 0;
while(a[i] < 0 && i<N_ELEMENTS) {
i++;
}
if (a[i] < 0) {
printf ("DEBUG: array with only negative numbers. Print the smallest negative number as the sum and we are done.\n");
}
int sum_p=0, sum_n = 0;
int largest_sum = 0;
while (i<N_ELEMENTS) {
if (a[i] > 0) {
sum_p += a[i];
}
else {
sum_n += a[i];
}
if (sum_p+sum_n > largest_sum) {
largest_sum = sum_p + sum_n;
}
if (sum_p+sum_n <= 0) {
// find the next positive number
while(a[i] < 0 && i<N_ELEMENTS) {
i++;
}
if (a[i] < 0 || i == N_ELEMENTS) {
break;
}
sum_p = 0;
sum_n = 0;
} else {
i++;
}
}
printf ("DEBUG: The largest consecutive sum = %d\n", largest_sum);
}
Run Code Online (Sandbox Code Playgroud)
你应该做的是尝试每一个可能的连续三个数字,并从中选择最好的类似的东西
int sum = 0;
int idx = 0
for(int i=0;i<size-2;i++){
if (A[i]+A[i+1]+A[i+2] > sum){
sum = A[i] + A[i+1] + A[i+2];
idx = i;
}
}
Run Code Online (Sandbox Code Playgroud)
答案是A [idx],A [idx + 1],A [idx + 2]
| 归档时间: |
|
| 查看次数: |
1454 次 |
| 最近记录: |