Challenge
Determine the largest contiguous sum of integers in a list.
Specifications
- The first argument is a path to a file.
- The file contains multiple lines.
- Each line is a test case represented by a comma separated list of integers.
- For each test case, find and print the largest contiguous sub-array sum.
Sample Input
-10,2,3,-2,0,5,-15
2,3,-2,-1,10
Sample Output
8
12
#include <stdio.h>
#include <string.h>
#define LINE_LENGTH 1024
#define MIN_INT -32768
int largest_contiguous_sum(int *array, int size) {
int max = MIN_INT;
int current_max = MIN_INT;
for (int i = 0; i < size; i++) {
current_max = current_max + array[i] > array[i] ? current_max + array[i] : array[i];
max = max > current_max ? max : current_max;
}
return max;
}
int compute_largest_contiguous_sum(char *line) {
char seperator[] = ",";
char *token;
int var;
int array[512];
int i = 0;
token = strtok(line, seperator);
while (token != NULL) {
sscanf(token, "%d", &var);
array[i++] = var;
token = strtok(NULL, seperator);
}
return largest_contiguous_sum(array, i);
}
int main(int argc, char *args[]) {
if (argc < 2) {
fprintf(stderr, "File path not provided. Exiting...\n");
return 1;
}
if (argc > 2) {
puts("Excessive arguments, only the first will be considered.");
}
FILE *file = fopen(args[1], "r");
if (file == NULL) {
perror("Error");
return 1;
}
char line[LINE_LENGTH];
while (fgets(line, LINE_LENGTH, file)) {
printf("%d\n", compute_largest_contiguous_sum(line));
}
fclose(file);
}
First time using strtok
and wondering if there was a better tool.
largest_contiguous_sum
just finds the largest contiguous sum which includes the first item inarray
. Have you tested the output of your program for a few sample inputs? Also, there is astd::max
function in<algorithm>
so you don't need to use those if statements to see which value is larger. \$\endgroup\$current max
. Its value is updated to the value at a specific point if that specific point is higher, e.g. -3,1,-2,4,1 would effectively 'start' at 4. As for test cases, this passes all the ones one the cited challenge site. \$\endgroup\$28
from5,5,5,-1,-1,5,5,5
? \$\endgroup\$