c - 查找数组中整数的最大连续和

标签 c arrays algorithm

我有这个实现,这个程序的结果是 100,但正确答案是 103。 有谁知道这个实现有什么问题,或者是否有更好的方法来查找数组中整数的最大连续和?

提前致谢。

#include <stdio.h>

int main(void) {
int a[] = { -3, 100, -4, -2, 9, -63, -200, 55 };
int max_sum, temp_sum, i, n = 12, t;
temp_sum = max_sum = a[0];
for (i = 1; i < n; i++) {
    if (a[i] > 0)
        temp_sum += a[i];
    else {
        t = 0;
        while (a[i] < 0 && i < n) {
            t += a[i];
            i++;
        }
        if (temp_sum + t > 0) {
            temp_sum = temp_sum + t + a[i];
            if (temp_sum > max_sum)
                max_sum = temp_sum;
        } else if (i < n)
            temp_sum = a[i];
    }
}
if (temp_sum > max_sum)
    max_sum = temp_sum;
printf("Maximum Numbers is %d \n", max_sum);
return 0;
}

最佳答案

您没有使用正确的索引:

演示请看这里:http://codepad.org/wbXZY5zP

int max_sum, temp_sum, i, n = 8, t;
temp_sum = max_sum = a[0];
for (i = 0; i < n; i++) {
    (...)
}

关于c - 查找数组中整数的最大连续和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10095375/

相关文章:

jQuery .each() 和 jQuery .post()

algorithm - Heapsort可以应用于最小堆数据结构吗?

c - 需要帮助理解指针和其他各种 C 东西

c - 椭圆曲线离散对数

arrays - 如果选择一定次数,Perl 从数组中删除项目

algorithm - List.mem 的复杂性

ios - After Effects Rotoscoping 笔刷算法

c - C 程序中读取日期和时间的正则表达式

c - 优化的 2x2 矩阵乘法 : Slow assembly versus fast SIMD

arrays - 如何比较结构和数组的值?