11
1
Given a sequence of integers find the largest sum of a subsequence (integers on consecutive positions) of the sequence. The subsequence can be empty (in which case the sum is 0).
Input is read from standard input, one integer per line. The largest sum must be written to standard output.
I wrote a small generator for you:
#include <stdio.h>
#include <assert.h>
/* From http://en.wikipedia.org/wiki/Random_number_generation */
unsigned m_w;
unsigned m_z;
unsigned get_random()
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w; /* 32-bit result */
}
int main(int argc, char **argv)
{
int i;
assert(argc == 3);
m_w = atoi(argv[1]);
m_z = atoi(argv[2]);
i = 10;
while (i--);
get_random();
i = atoi(argv[2]);
while (i--)
printf("%d\n", (int) get_random() << 8 >> 22);
return 0;
}
Examples:
$ printf "1\n2\n-1\n4\n" | ./sum
6
$ printf "0\n-2\n-3\n" | ./sum
0
$ ./a.out 1 1 | ./sum
387
$ ./a.out 1 10 | ./sum
571
$ ./a.out 1 100 | ./sum
5867
$ ./a.out 1 1000 | ./sum
7531
$ ./a.out 1 10000 | ./sum
27268
$ ./a.out 1 100000 | ./sum
101332
$ ./a.out 1 1000000 | ./sum
187480
$ ./a.out 1 10000000 | ./sum
666307
./sum
is my solution./a.out
is the generator
Your solution must run in reasonable time for all tests above (mine runs in 1.2s on the last test case).
Shortest code wins.
Edit: Please provide an example run on one of the tests above.
assert(argc==3) :-) That's what I call a user friendly program! :-) – Emanuel Landeholm – 2015-02-23T11:45:52.873
You need
#include <stdlib.h>
foratoi()
. – Paul R – 2011-07-03T13:46:09.653My own c solution take 4 seconds for last test case, very interested about your solution. – Dongshengcn – 2011-07-03T23:16:56.600
Make sure you write first to a file and then read from file, and not use pipes. – Alexandru – 2011-07-04T08:42:33.477
I guess there is an error in your generator, line 25,
while (i--);
shouldn't end in an semicolon, should it? – user unknown – 2012-01-02T05:37:02.240