Find the maximum sequential sum of integers in an array

I have this implementation, the result of this program is 100, but the correct answer is 103. who knows what is wrong with this implementation or is there a better way to find the maximum sequential sum of integers in an array?

Thanks in advance.

#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;
}
+3
source share
4 answers

You are not using the correct indexes:

see here for a demo: 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++) {
    (...)
}
+6
source

I suggest the Kadane algorithm . In C ++, it will be something like this (untested):

int maxSubarray(std::vector<int> a) {
    int maxAll = 0, maxHere = 0;
    for (size_t i = 0; i < a.size(); ++i) {
        maxHere = std::max(a[i], maxHere + a[i]);
        maxAll = std::max(maxAll, maxHere);
    }
    return maxAll;
}
+4
source

, . , , , , , ( ).

, , a[i] < 0 && temp_sum + t < 0 - .

} else if (i < n) {
    temp_sum = a[i];
    if (temp_sum > max_sum)
       max_sum = temp_sum;
}
+1

If he is looking for the largest consecutive sum that does not start at index 0, the easiest way would be to have two loops

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

All Articles