Re: Program to find the largest sum of contiguous integers in the array. O(n)
Yes, the solution provided above is incorrect. I came to this website looking for the solution and finally ended up writing it myself. Hope this is useful for someone else.
Here is a working solution. Set the array "a" and N_ELEMENTS accordingly. Some cases are not covered but should be an easy fix.
#include <stdio.h>
#define N_ELEMENTS 7
int main() {
int a[N_ELEMENTS] = {-1, 2, -3, 2, 0, 5, -11 }; // if you change the array, make sure you change N_ELEMENTS
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);
Re: Program to find the largest sum of contiguous integers in the array. O(n)
Umm you need a dynamic programming algorithm that uses subproblems and memoization to solve this adequately. Pretty sure all of the "solutions" listed in here are wrong.