Program to find the largest sum of contiguous integers in
the array. O(n)

Answer Posted / jjaspirin

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);

}

Is This Answer Correct ?    3 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

write a function to give demostrate the functionality of 3d in 1d. function prototye: change(int value,int indexX,int indexY,int indexZ, int [] 1dArray); value=what is the date; indexX=x-asix indexY=y-axis indexZ=z-axis and 1dArray=in which and where the value is stored??

4140


how to create a 3x3 two dimensional array that will give you the sums on the left and bottom columns

3117


What is full form of PEPSI

1865


write a c program to input initial & final time in the format hh:mm and find the time intervel between them? Ex inputs are initial 06:30 final 00:05 and 23:22 final 22.30

2219


How can you relate the function with the structure? Explain with an appropriate example.

2915






Write a routine to implement the polymarker function

4375


What is the difference between proc means and proc tabulate ? explain with a simple example when you have to use means or tabulate?

3708


why nlogn is the lower limit of any sort algorithm?

2373


how to test pierrot divisor

2256


What is data _null_? ,Explain with code when u need to use it in data step programming ?

2820


How to palindrom string in c language?

8836


can you use proc sql to manpulate a data set or would u prefer to use proc report ? if so why ? make up an example and explain in detail

2325


Cluster head selection in Wireless Sensor Network using C programming language.

3107


Develop a routine to reflect an object about an arbitrarily selected plane

2994


Write a program to model an exploding firecracker in the xy plane using a particle system

3686